Empty Label ChoiceField Django

Nick B picture Nick B · Jan 26, 2013 · Viewed 47.5k times · Source

How do you make ChoiceField's label behave like ModelChoiceField? Is there a way to set an empty_label, or at least show a blank field?

Forms.py:

    thing = forms.ModelChoiceField(queryset=Thing.objects.all(), empty_label='Label')
    color = forms.ChoiceField(choices=COLORS)
    year = forms.ChoiceField(choices=YEAR_CHOICES)

I have tried the solutions suggested here:

Stack Overflow Q - Setting CHOICES = [('','All')] + CHOICES resulted in an internal server error.

Stack Overflow Q2 - After defining ('', '---------'), in my choices, still defaulted to the first item in the list, not the ('', '---------'), choice.

Gist - Tried using EmptyChoiceField defined here, but did not work using Django 1.4.

But none of these have worked for me.. How would you solve this issue? Thanks for your ideas!

Answer

Fiver picture Fiver · Jan 27, 2013

See the Django 1.11 documentation on ChoiceField. The 'empty value' for the ChoiceField is defined as the empty string '', so your list of tuples should contain a key of '' mapped to whatever value you want to show for the empty value.

### forms.py
from django.forms import Form, ChoiceField

CHOICE_LIST = [
    ('', '----'), # replace the value '----' with whatever you want, it won't matter
    (1, 'Rock'),
    (2, 'Hard Place')
]

class SomeForm (Form):

    some_choice = ChoiceField(choices=CHOICE_LIST, required=False)

Note, you can avoid a form error if you want the form field to be optional by using required=False

Also, if you already have a CHOICE_LIST without an empty value, you can insert one so it shows up first in the form drop-down menu:

CHOICE_LIST.insert(0, ('', '----'))