In Django's Model, enter any value in choices.

Asked 2 years ago, Updated 2 years ago, 94 views

I am using the Django 1.6 model.
I would like to have multiple selections and any value.

I borrowed it from the official document, but
With choices, you can select more than one as follows

 from django.db import models

Class Person (models.Model):
    GENDER_CHOICES=(
        (u'M', u'Male'),
        (u'F', u'Female'),
    )
    name=models.CharField(max_length=60)
    gender=models.CharField(max_length=2,choices=GENDER_CHOICES)

However, in addition to M and F, when users want to add something like "u'unanswered'",
Unable to enter.
Is the only way to achieve this is to customize the template side?

python django

2022-09-30 20:34

2 Answers

If default=None (or u'unanswered'), wouldn't it go?

gender=models.CharField(max_length=2, 
                          default=u 'Unanswered',
                          choices=GENDER_CHOICES)

Also, u'unanswered' should be in GENDER_CHOICES if the value is acceptable.

GENDER_CHOICES=(
    (u'M', u'Male'),
    (u'F', u'Female'),
    (u'N', u'unanswered'),
)


2022-09-30 20:34

If you have a web browser that supports datalist tags, you can use datalist tags to "make multiple choices and include any value."

However, the datalist tag itself is not supported by Django 1.6 (as is the case with the current 1.10), so custom widgets and templates must work together.
Please refer to the answers that are being implemented by defining the custom widget in our Stackoverflow home.
In this case, you do not need to pass the choices parameter to django.db.models.CharField because the Model must store any value in the DB.

Unfortunately, 2017/3 Safari does not currently support datalist tags, so if you support Safari, you need to do so with JavaScript.
Consider adopting awesomeplate.


2022-09-30 20:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.