Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #5957 -- Enforce the "required" attribute on BooleanField in ne…

…wforms.

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
  • Loading branch information...
commit abcf1cb36d0bf22d5f2efa4dd85183a0341b33f8 1 parent 8e816c8
Malcolm Tredinnick authored June 30, 2008
10  django/newforms/fields.py
@@ -535,13 +535,17 @@ class BooleanField(Field):
535 535
 
536 536
     def clean(self, value):
537 537
         """Returns a Python boolean object."""
538  
-        super(BooleanField, self).clean(value)
539 538
         # Explicitly check for the string 'False', which is what a hidden field
540 539
         # will submit for False. Because bool("True") == True, we don't need to
541 540
         # handle that explicitly.
542 541
         if value == 'False':
543  
-            return False
544  
-        return bool(value)
  542
+            value = False
  543
+        else:
  544
+            value = bool(value)
  545
+        super(BooleanField, self).clean(value)
  546
+        if not value and self.required:
  547
+            raise ValidationError(self.error_messages['required'])
  548
+        return value
545 549
 
546 550
 class NullBooleanField(BooleanField):
547 551
     """
12  tests/regressiontests/forms/fields.py
@@ -937,18 +937,24 @@
937 937
 >>> f.clean(True)
938 938
 True
939 939
 >>> f.clean(False)
940  
-False
  940
+Traceback (most recent call last):
  941
+...
  942
+ValidationError: [u'This field is required.']
941 943
 >>> f.clean(1)
942 944
 True
943 945
 >>> f.clean(0)
944  
-False
  946
+Traceback (most recent call last):
  947
+...
  948
+ValidationError: [u'This field is required.']
945 949
 >>> f.clean('Django rocks')
946 950
 True
947 951
 
948 952
 >>> f.clean('True')
949 953
 True
950 954
 >>> f.clean('False')
951  
-False
  955
+Traceback (most recent call last):
  956
+...
  957
+ValidationError: [u'This field is required.']
952 958
 
953 959
 >>> f = BooleanField(required=False)
954 960
 >>> f.clean('')

0 notes on commit abcf1cb

Please sign in to comment.
Something went wrong with that request. Please try again.