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.
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'
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With