Login

Strict Boolean Form Field

Author:
powderflask
Posted:
June 20, 2019
Language:
Python
Version:
2.1
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

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.