Django forms: Adding a blank option to a required choice field

Recently I came across a problem where I had a django form choicefield that needed to be required, but also needed a blank choice in case the user didn’t see the field and incorrectly submitted the first value. I saw a stack overflow post recommending to make a clean method to check that the first choice isn’t selected. That post is here:

http://stackoverflow.com/questions/5289491/blank-option-in-required-choicefield

… but a better way to do this is to simply leave the value of the blank choice as an empty string, which will invalidate the form without any extra clean method, like below:


CHOICES_WITH_BLANK = (
    ('', '--------'),
    ('1', 'choice one'),
    ('2', 'choice two'),
)

class ChoiceForm(forms.Form):
     choice_field = forms.ChoiceField(choices=CHOICES_WITH_BLANK)

One thought on “Django forms: Adding a blank option to a required choice field”

Leave a Reply

Your email address will not be published. Required fields are marked *