pythonflaskwtformshtml-input

Make a SelectField select nothing by default


I have a Form containing a SelectField, something like this:

CHOICES = [
    ('A', 'Apple'),
    ('B', 'Ball'),
    ('C', 'Cat'),
]

class MyForm(Form):
    choice = SelectField(choices=CHOICES)
    # ...other fields here... #

When I render the form, it shows the SelectField with 'Apple' chosen by default. But I want to have nothing chosen in the beginning, so that the user is forced to make the choice themselves.

Is there a way to render a blank choice, which is displayed by default but is not a valid choice once the form is submitted?


Solution

  • An option with the value None will display in the form but is still invalid when submitted. You can set it as the default option like this:

    CHOICES = [
        (None, ''), # <-- This option is invalid when submitted
        ('A', 'Apple'),
        ('B', 'Ball'),
        ('C', 'Cat'),
    ]
    
    class MyForm(Form):
        choice = SelectField(choices=CHOICES, default=None)
        # ...other fields here... #
    

    Adding default=None to the SelectField is optional, since that's the default behaviour anyway.

    You can also add a string to the value, like (None, '--') or (None, 'Please select an option'). That option will still be invalid.

    Note: I suspect this behaviour is nothing to do with the None object itself, but happens because it gets coerced to 'None' (type unicode) when submitted from the form and hence does not match the original None (type NoneType).