WTForms SelectField not correctly enforced 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.dataalways True. I suspect that I do not understand how coercion works.

+5
source share
1 answer

As long as you pass the bools to the selection, only strings are used in the HTML values. Thus, you will have a choice of 'True'and 'False'. Both are non-empty strings, so when a value is cast to a value bool, they are both evaluated as True. You will need to use another called object that does the right thing for the string 'False'.

InputRequired DataRequired. , , , .

SelectField(
    choices=[(True, 'Yes'), (False, 'No')],
    validators=[InputRequired()],
    coerce=lambda x: x == 'True'
)
+2

Source: https://habr.com/ru/post/1613773/


All Articles