WTForms BooleanField Value And Validation

February 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 BooleanField

class 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:
   = False
   = 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.default
        elif valuelist[0] in self.false_values:
   = False
   = True

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

from wtforms import validators

class 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])])


This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.