[Django]-Django empty label in choice field – no queryset

2👍

Setting what you want on the form is a more correct way to do achieve what you want. In Django, models contain the essential fields and behaviors of the data you’re storing. That said, they define how your information is structured in the database.

1. I didn’t check it, but your first option

COLOR_CHOICES = (
    ('', '---Please select your color---'),
    (BLUE, 'Blue'),
    (RED, 'Red'),
    (GREEN, 'Green'),

my_color = models.CharField(max_length=5, choices=COLOR_CHOICES)

might not work, as your first choice is an empty string, but your my_color field does not contain the blank=True argument. This means it won’t allow saving the empty string to the database. But in case you want this field to be mandatory, then your definition of the empty choice should not be here, as it does not bring any added value as it does not hold any additional information regarding your data structure.

2. Your second option is definitely not the way to go [1]:

Avoid using null on string-based fields such as CharField and TextField because empty string values will always be stored as empty strings, not as NULL. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL.

3. Your third option looks good. I didn’t work for some time with django forms, but if your code works, the Form is a more suitable place to define how your form should look like than doing it in your models, so go for that option.

Or take a look at the solutions from the SO question linked in your post and implement those.

Good luck!

👤iulian

2👍

So you want to set empty_label for all model Forms, created from your? Adding an empty option in choices is fine, its even stated in the docs.

Unless blank=False is set on the field along with a default then a
label containing "———" will be rendered with the select box. To
override this behavior, add a tuple to choices containing None; e.g.
(None, ‘Your String For Display’). Alternatively, you can use an empty
string instead of None where this makes sense – such as on a
CharField.

But in order to stop showing the default one you need to set blank=False. So give a try to something like this:

class MyColorModel(models.Model):
    BLUE = 'blue'
    RED = 'red'
    GREEN = 'green'
    COLOR_CHOICES = (
        ('', '---Please select your color---')
        (BLUE, 'Blue'),
        (RED, 'Red'),
        (GREEN, 'Green'))

   my_color = models.CharField(max_length=5, choices=COLOR_CHOICES, blank=False, null=False, default='')

But in my opinion the best way to do it is just to set empty_label on the form.field.

def __init__(*args, **kwargs):
    super(MyColorForm, self).__init__(*args, **kwargs)
    self.fields['my_color'].empty_label = '---Please select your color---'
👤Todor

Leave a comment