Login

Strict Boolean Form Field

Author:
powderflask
Posted:
June 20, 2019
Language:
Python
Version:
2.1
Tags:
form_field
Score:
0 (after 0 ratings)

A form field for a Boolean that forces the user to make a choice from a list of choices.

Use Case

You have a Yes/No question the user must answer, but they may answer it yes or no. You don't want to supply a default because your need to force the user to actively select their answer. If they do not select an answer, the field should raise a validation error, like "This field is required".

Normal BooleanField logic is based on a "checkbox", which, when "required" is required to be checked. This logic assumes that an empty value is the same as False -- in fact, there is no way for validators to distinguish between the empty value and False.

Based on excellent suggestion from Peter DeGlopper: https://stackoverflow.com/a/56677670/1993525

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from django.forms import NullBooleanField, TypedChoiceField

class StrictBooleanField(TypedChoiceField):

    def __init__(self, *args, coerce=lambda val: bool(val), empty_value='', **kwargs):
        super().__init__(*args, coerce=coerce, empty_value=empty_value, **kwargs)
        
    def to_python(self, value):
        """
        Explicitly validate empty / missing values, otherwise normal conversion
        """
        value = NullBooleanField.to_python(self, value)
        if value is None:
            raise ValidationError(_('Invalid Boolean value %(value)s'), params={'value': value}, code='invalid')          

        return value

More like this

Comments

Please login first before commenting.