Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blank option in required ChoiceField

I want my ChoiceField in ModelForm to have a blank option (------) but it's required.

I need to have blank option to prevent user from accidentally skipping the field thus select the wrong option.

like image 603
willwill Avatar asked Mar 13 '11 12:03

willwill


1 Answers

This works for at least 1.4 and later:

CHOICES = (
    ('', '-----------'),
    ('foo', 'Foo')
)

class FooForm(forms.Form):
    foo = forms.ChoiceField(choices=CHOICES)

Since ChoiceField is required (by default), it will complain about being empty when first choice is selected and wouldn't if second.

It's better to do it like this than the way Yuji Tomita showed, because this way you use Django's localized validation messages.

like image 87
Ctrl-C Avatar answered Oct 07 '22 15:10

Ctrl-C