Django

Code

Changeset 7799

Show
Ignore:
Timestamp:
06/30/08 05:44:56 (1 year ago)
Author:
mtredinnick
Message:

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.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/django/newforms/fields.py

    r7645 r7799  
    536536    def clean(self, value): 
    537537        """Returns a Python boolean object.""" 
    538         super(BooleanField, self).clean(value) 
    539538        # Explicitly check for the string 'False', which is what a hidden field 
    540539        # will submit for False. Because bool("True") == True, we don't need to 
    541540        # handle that explicitly. 
    542541        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 
    545549 
    546550class NullBooleanField(BooleanField): 
  • django/trunk/tests/regressiontests/forms/fields.py

    r7776 r7799  
    938938True 
    939939>>> f.clean(False) 
    940 False 
     940Traceback (most recent call last): 
     941... 
     942ValidationError: [u'This field is required.'] 
    941943>>> f.clean(1) 
    942944True 
    943945>>> f.clean(0) 
    944 False 
     946Traceback (most recent call last): 
     947... 
     948ValidationError: [u'This field is required.'] 
    945949>>> f.clean('Django rocks') 
    946950True 
     
    949953True 
    950954>>> f.clean('False') 
    951 False 
     955Traceback (most recent call last): 
     956... 
     957ValidationError: [u'This field is required.'] 
    952958 
    953959>>> f = BooleanField(required=False)