WTForms BooleanField Value And Validation

Feb 13, 2018

By default, BooleanField only accept ('false', '') as False, any other value is assumed to be True. 0, '0' or False shall be evaluated as True in this case.

You can change the default behaviour by passing in false_values parameters.

from wtforms.fields as BooleanFieldclass ReminderForm(BaseForm):    # '' will not be considered as False    is_approved = BooleanField(false_values=(False, 'false', 0, '0'))

Another interesting fact is default BooleanField can only be True or False, never None.

class BooleanField(Field):    ...    def process_formdata(self, valuelist):        if not valuelist or valuelist[0] in self.false_values:            self.data = False        else:            self.data = True

Alternatively, you can create your own implementation which allow True, False and None (default).

class MyBooleanField(wtf.BooleanField):    def __init__(self, label=None, validators=None, false_values=None, **kwargs):        # don't accept blank as False, so that default will trigger        super(MyBooleanField, self).__init__(label, validators, (False, 'false', 0, '0'), **kwargs)    def process_formdata(self, valuelist):        if not valuelist or valuelist[0] == '' or valuelist[0] is None:            self.data = self.default        elif valuelist[0] in self.false_values:            self.data = False        else:            self.data = True

When you put in Required validator, BooleanField expect True value to pass validation test (will fail if False value).

from wtforms import validatorsclass ReminderForm(BaseForm):    # same behaviour with validators.DataRequired() and validators.Required() in this case    is_approved = MyBooleanField(validators=[validators.InputRequired()])

If you just want a value to be pass in (either True or False, but not None), use our custom MyBoolean implementation with AnyOf validator.

MyBooleanField(validators=[validators.AnyOf([True, False])])

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.