Ticket #6362: 6362.normalize-kwarg.diff
File 6362.normalize-kwarg.diff, 6.8 KB (added by , 16 years ago) |
---|
-
django/newforms/fields.py
56 56 creation_counter = 0 57 57 58 58 def __init__(self, required=True, widget=None, label=None, initial=None, 59 help_text=None, error_messages=None ):59 help_text=None, error_messages=None, normalize=None): 60 60 # required -- Boolean that specifies whether the field is required. 61 61 # True by default. 62 62 # widget -- A Widget class, or instance of a Widget class, that should … … 74 74 label = smart_unicode(label) 75 75 self.required, self.label, self.initial = required, label, initial 76 76 self.help_text = smart_unicode(help_text or '') 77 self.normalize = normalize 77 78 widget = widget or self.widget 78 79 if isinstance(widget, type): 79 80 widget = widget() … … 106 107 107 108 Raises ValidationError for any errors. 108 109 """ 110 if self.normalize: 111 value = self.normalize(value) 109 112 if self.required and value in EMPTY_VALUES: 110 113 raise ValidationError(self.error_messages['required']) 111 114 return value … … 136 139 137 140 def clean(self, value): 138 141 "Validates max_length and min_length. Returns a Unicode object." 139 super(CharField, self).clean(value)142 value = super(CharField, self).clean(value) 140 143 if value in EMPTY_VALUES: 141 144 return u'' 142 145 value = smart_unicode(value) … … 168 171 Validates that int() can be called on the input. Returns the result 169 172 of int(). Returns None for empty values. 170 173 """ 171 super(IntegerField, self).clean(value)174 value = super(IntegerField, self).clean(value) 172 175 if value in EMPTY_VALUES: 173 176 return None 174 177 try: … … 197 200 Validates that float() can be called on the input. Returns a float. 198 201 Returns None for empty values. 199 202 """ 200 super(FloatField, self).clean(value)203 value = super(FloatField, self).clean(value) 201 204 if not self.required and value in EMPTY_VALUES: 202 205 return None 203 206 try: … … 232 235 than max_digits in the number, and no more than decimal_places digits 233 236 after the decimal point. 234 237 """ 235 super(DecimalField, self).clean(value)238 value = super(DecimalField, self).clean(value) 236 239 if not self.required and value in EMPTY_VALUES: 237 240 return None 238 241 value = smart_str(value).strip() … … 277 280 Validates that the input can be converted to a date. Returns a Python 278 281 datetime.date object. 279 282 """ 280 super(DateField, self).clean(value)283 value = super(DateField, self).clean(value) 281 284 if value in EMPTY_VALUES: 282 285 return None 283 286 if isinstance(value, datetime.datetime): … … 310 313 Validates that the input can be converted to a time. Returns a Python 311 314 datetime.time object. 312 315 """ 313 super(TimeField, self).clean(value)316 value = super(TimeField, self).clean(value) 314 317 if value in EMPTY_VALUES: 315 318 return None 316 319 if isinstance(value, datetime.time): … … 349 352 Validates that the input can be converted to a datetime. Returns a 350 353 Python datetime.datetime object. 351 354 """ 352 super(DateTimeField, self).clean(value)355 value = super(DateTimeField, self).clean(value) 353 356 if value in EMPTY_VALUES: 354 357 return None 355 358 if isinstance(value, datetime.datetime): … … 444 447 super(FileField, self).__init__(*args, **kwargs) 445 448 446 449 def clean(self, data, initial=None): 447 super(FileField, self).clean(initial or data)450 value = super(FileField, self).clean(initial or data) 448 451 if not self.required and data in EMPTY_VALUES: 449 452 return None 450 453 elif not data and initial: … … 572 575 573 576 class BooleanField(Field): 574 577 widget = CheckboxInput 575 576 def clean(self, value): 577 """Returns a Python boolean object.""" 578 def __init__(self, normalize=None, *args, **kwargs): 578 579 # Explicitly check for the string 'False', which is what a hidden field 579 580 # will submit for False. Because bool("True") == True, we don't need to 580 581 # handle that explicitly. 581 if value == 'False': 582 value = False 582 bool_norm = lambda value: value != 'False' and bool(value) 583 if normalize: 584 norm_func = lambda value: bool_norm(normalize(value)) 583 585 else: 584 value = bool(value) 585 super(BooleanField, self).clean(value) 586 norm_func = bool_norm 587 super(BooleanField, self).__init__(normalize=norm_func, *args, **kwargs) 588 589 def clean(self, value): 590 """Returns a Python boolean object.""" 591 value = super(BooleanField, self).clean(value) 586 592 if not value and self.required: 587 593 raise ValidationError(self.error_messages['required']) 588 594 return value … … 679 685 Validates the given value against all of self.fields, which is a 680 686 list of Field instances. 681 687 """ 682 super(ComboField, self).clean(value)688 value = super(ComboField, self).clean(value) 683 689 for field in self.fields: 684 690 value = field.clean(value) 685 691 return value -
tests/regressiontests/forms/fields.py
104 104 >>> f.clean('1234567890a') 105 105 u'1234567890a' 106 106 107 Normalize away leading and trailing whitspace: 108 >>> f = CharField(normalize=lambda x: x.strip()) 109 >>> f.clean(" \t") 110 Traceback (most recent call last): 111 ... 112 ValidationError: [u'This field is required.'] 113 107 114 # IntegerField ################################################################ 108 115 109 116 >>> f = IntegerField() -
docs/newforms.txt
1132 1132 In the `built-in Field classes`_ section below, each ``Field`` defines the 1133 1133 error message keys it uses. 1134 1134 1135 ``normalize`` 1136 ~~~~~~~~~~~~~ 1137 1138 **New in Django development version** 1139 1140 The ``normalize`` argument lets you normalize the input data before it is validated. 1141 A common use-case is stripping leading and trailinig whitespace from CharFields:: 1142 1143 >>> foo = forms.CharField(normalize=lambda x: x.strip()) 1144 >>> foo.clean(' ') 1145 Traceback (most recent call last): 1146 ... 1147 ValidationError: [u'This field is required.'] 1148 1135 1149 Dynamic initial values 1136 1150 ---------------------- 1137 1151