Fixed #5957 -- Enforce the "required" attribute on BooleanField in newforms.
This has been the documented behaviour for ages, but it wasn't correctly implemented. A required BooleanField must be True/checked, since False values aren't submitted. Ideal for things like "terms of service" agreements. Backwards incompatible (since required=True is the default for all fields). Unclear who the original patch was from, but Tai Lee and Alex have kept it up to date recently. git-svn-id: http://code.djangoproject.com/svn/django/trunk@7799 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
parent
8e816c8304
commit
abcf1cb36d
|
@ -535,13 +535,17 @@ class BooleanField(Field):
|
||||||
|
|
||||||
def clean(self, value):
|
def clean(self, value):
|
||||||
"""Returns a Python boolean object."""
|
"""Returns a Python boolean object."""
|
||||||
super(BooleanField, self).clean(value)
|
|
||||||
# Explicitly check for the string 'False', which is what a hidden field
|
# Explicitly check for the string 'False', which is what a hidden field
|
||||||
# will submit for False. Because bool("True") == True, we don't need to
|
# will submit for False. Because bool("True") == True, we don't need to
|
||||||
# handle that explicitly.
|
# handle that explicitly.
|
||||||
if value == 'False':
|
if value == 'False':
|
||||||
return False
|
value = False
|
||||||
return bool(value)
|
else:
|
||||||
|
value = bool(value)
|
||||||
|
super(BooleanField, self).clean(value)
|
||||||
|
if not value and self.required:
|
||||||
|
raise ValidationError(self.error_messages['required'])
|
||||||
|
return value
|
||||||
|
|
||||||
class NullBooleanField(BooleanField):
|
class NullBooleanField(BooleanField):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -937,18 +937,24 @@ ValidationError: [u'This field is required.']
|
||||||
>>> f.clean(True)
|
>>> f.clean(True)
|
||||||
True
|
True
|
||||||
>>> f.clean(False)
|
>>> f.clean(False)
|
||||||
False
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValidationError: [u'This field is required.']
|
||||||
>>> f.clean(1)
|
>>> f.clean(1)
|
||||||
True
|
True
|
||||||
>>> f.clean(0)
|
>>> f.clean(0)
|
||||||
False
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValidationError: [u'This field is required.']
|
||||||
>>> f.clean('Django rocks')
|
>>> f.clean('Django rocks')
|
||||||
True
|
True
|
||||||
|
|
||||||
>>> f.clean('True')
|
>>> f.clean('True')
|
||||||
True
|
True
|
||||||
>>> f.clean('False')
|
>>> f.clean('False')
|
||||||
False
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValidationError: [u'This field is required.']
|
||||||
|
|
||||||
>>> f = BooleanField(required=False)
|
>>> f = BooleanField(required=False)
|
||||||
>>> f.clean('')
|
>>> f.clean('')
|
||||||
|
|
Loading…
Reference in New Issue