WTForms SelectField not properly coercing for booleans
Asked Answered
K

2

9

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.

Kaplan answered 30/10, 2015 at 5:52 Comment(0)
J
12

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'
)
Justinjustina answered 30/10, 2015 at 6:36 Comment(0)
M
0

I know this is a quite old question but never the less:


def coerce_bool(x):
    if isinstance(x, str):
        return x == "True" if x != "None" else None
    else:
        return bool(x) if x is not None else None

wtf.SelectField(
    choices=[(None, ""),(True, "Yes"), (False, "No")],
    coerce=coerce_bool
)

SelectField calls coerce in both directions:

  • when processing python data applied to field, and
  • when processing data over the wire from the form

that is the reason for checking is the value str or not and making an explicit comparison of values.

Muhammadan answered 12/11, 2022 at 16:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.