Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WTForms SelectField not properly coercing for booleans

Here is my code:

class ChangeOfficialForm(Form):
    is_official = SelectField(
        'Officially Approved',
        choices=[(True, 'Yes'), (False, 'No')],
        validators=[DataRequired()],
        coerce=bool
    )
    submit = SubmitField('Update status')

For some reason, is_official.data is always True. I suspect that I am misunderstanding how coercing works.

like image 522
Ben Sandler Avatar asked Oct 30 '15 05:10

Ben Sandler


1 Answers

While you've passed bools to the choices, only strings are used in HTML values. So you'll have the choice values 'True' and 'False'. Both of these are non-empty strings, so when the value is coerced with bool, they both evaluate to True. You'll need to use a different callable that does the right thing for the 'False' string.

You also need to use the InputRequired validator instead of DataRequired. Checking the data fails if the data is False-like, while checking the input will validate as long as the input is not empty.

SelectField(
    choices=[(True, 'Yes'), (False, 'No')],
    validators=[InputRequired()],
    coerce=lambda x: x == 'True'
)
like image 88
davidism Avatar answered Sep 28 '22 00:09

davidism