Blank option in required ChoiceField

前端 未结 4 1125
醉梦人生
醉梦人生 2021-02-20 09:35

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 t

4条回答
  •  执笔经年
    2021-02-20 09:46

    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.

提交回复
热议问题