Login

RequiredNullBooleanField

Author:
wwu.housing
Posted:
March 24, 2009
Language:
Python
Version:
1.0
Score:
3 (after 3 ratings)

In our situation, we want the user to choose either yes or no. The only requirement is that they fill out the form. It is not required that they answer True/Yes.

The BooleanField treats None and False as False; The NullBooleanField distinguishes between None and False, but it doesn't raise any validation errors.

Subclassing the NullBooleanField was better than overriding the clean method on all of our NullBooleanField instances.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# fields.py
from django import forms

class RequiredNullBooleanField(forms.NullBooleanField):
    def clean(self, value):
        value = super(RequiredNullBooleanField, self).clean(value)
        if value is None:
            raise forms.ValidationError("This field is required.")
        return value


# forms.py
from django import forms
from project.fields import RequiredNullBooleanField

class MyForm(forms.Form):
    question = RequiredNullBooleanField(label="Have you ever travelled in an airplane?", 
                                        widget=forms.RadioSelect(choices=[(True, "Yes"), (False, "No")]))

More like this

  1. A wrapper around cache_page making it optional by rixx 2 days, 2 hours ago
  2. Treat empty value on DateRangeFilter as a filter for non filled dates by kmmbvnr 1 month, 1 week ago
  3. Django Settings Assignment Expressions aka Walrus Operator example by webology 2 months, 1 week ago
  4. codigo alto nivel by MrRocklion 4 months, 1 week ago
  5. Load template from specific app by Krzysiek555 4 months, 4 weeks ago

Comments

Please login first before commenting.