Ticket #6362: 6362-default-for-ChadFields.diff

File 6362-default-for-ChadFields.diff, 7.7 KB (added by Alex Kamedov, 13 years ago)

Strip leading and trailinig whitespace for CharFields

  • django/forms/fields.py

    diff --git a/django/forms/fields.py b/django/forms/fields.py
    index 113a5aa..ea9e6dc 100644
    a b class Field(object):  
    5454
    5555    def __init__(self, required=True, widget=None, label=None, initial=None,
    5656                 help_text=None, error_messages=None, show_hidden_initial=False,
    57                  validators=[], localize=False):
     57                 validators=[], localize=False, normalize=None):
    5858        # required -- Boolean that specifies whether the field is required.
    5959        #             True by default.
    6060        # widget -- A Widget class, or instance of a Widget class, that should
    class Field(object):  
    8282            self.help_text = u''
    8383        else:
    8484            self.help_text = smart_unicode(help_text)
     85        self.normalize = normalize
    8586        widget = widget or self.widget
    8687        if isinstance(widget, type):
    8788            widget = widget()
    class Field(object):  
    149150        Raises ValidationError for any errors.
    150151        """
    151152        value = self.to_python(value)
     153        if self.normalize:
     154            value = self.normalize(value)
    152155        self.validate(value)
    153156        self.run_validators(value)
    154157        return value
    class CharField(Field):  
    186189            self.validators.append(validators.MinLengthValidator(min_length))
    187190        if max_length is not None:
    188191            self.validators.append(validators.MaxLengthValidator(max_length))
     192        if self.normalize is None:
     193            self.normalize = lambda value: value.strip()
    189194
    190195    def to_python(self, value):
    191196        "Returns a Unicode object."
    class DateTimeField(BaseTemporalField):  
    427432        return datetime.datetime.strptime(value, format)
    428433
    429434class RegexField(CharField):
    430     def __init__(self, regex, max_length=None, min_length=None, error_message=None, *args, **kwargs):
     435    def __init__(self, regex, max_length=None, min_length=None, error_message=None, normalize=False,  *args, **kwargs):
    431436        """
    432437        regex can be either a string or a compiled regular expression object.
    433438        error_message is an optional error message to use, if
    class RegexField(CharField):  
    438443            error_messages = kwargs.get('error_messages') or {}
    439444            error_messages['invalid'] = error_message
    440445            kwargs['error_messages'] = error_messages
    441         super(RegexField, self).__init__(max_length, min_length, *args, **kwargs)
     446        super(RegexField, self).__init__(max_length, min_length, normalize=normalize, *args, **kwargs)
    442447        if isinstance(regex, basestring):
    443448            regex = re.compile(regex)
    444449        self.regex = regex
    class EmailField(CharField):  
    450455    }
    451456    default_validators = [validators.validate_email]
    452457
    453     def clean(self, value):
    454         value = self.to_python(value).strip()
    455         return super(EmailField, self).clean(value)
    456 
    457458class FileField(Field):
    458459    widget = ClearableFileInput
    459460    default_error_messages = {
  • docs/ref/forms/fields.txt

    diff --git a/docs/ref/forms/fields.txt b/docs/ref/forms/fields.txt
    index 66c05e5..c4df0ba 100644
    a b as the rendered output.  
    278278See the :ref:`format localization <format-localization>` documentation for
    279279more information.
    280280
     281``normalize``
     282~~~~~~~~~~~~
     283
     284.. versionadded:: New in Django development version
     285
     286.. attribute:: Field.normalize
     287
     288The ``normalize`` argument lets you normalize the input data before it is validated.
     289A common use-case is stripping leading and trailinig whitespace from CharFields::
     290
     291    >>> foo = forms.CharField(normalize=lambda x: x.strip())
     292    >>> foo.clean('   ')
     293    Traceback (most recent call last):
     294      ...
     295    ValidationError: [u'This field is required.']
     296
     297This behavior for CharField enabled by default. Set `normalize=False`` to disable it.
     298
     299    >>> foo = forms.CharField(normalize=False)
     300    >>> foo.clean('   ')
     301    u'   '
     302
     303
    281304.. _built-in fields:
    282305
    283306Built-in ``Field`` classes
    For each field, we describe the default widget used if you don't specify  
    317340
    318341    * Default widget: ``TextInput``
    319342    * Empty value: ``''`` (an empty string)
    320     * Normalizes to: A Unicode object.
     343    * Normalizes to: A Unicode object with stripped leading and trailinig whitespace.
     344      Set ``normalize=False`` to disable stripping spaces or set
     345      ``normilize=your_callable_name`` to change normalization behavior.
    321346    * Validates ``max_length`` or ``min_length``, if they are provided.
    322347      Otherwise, all inputs are valid.
    323348    * Error message keys: ``required``, ``max_length``, ``min_length``
    Takes four optional arguments:  
    481506
    482507    * Default widget: ``TextInput``
    483508    * Empty value: ``''`` (an empty string)
    484     * Normalizes to: A Unicode object.
    485     * Validates that the given value is a valid email address, using a
     509    * Normalizes to: A Unicode object with stripped leading and trailinig whitespace.
     510      Set ``normalize=False`` to disable stripping spaces or set
     511      ``normilize=your_callable_name`` to change normalization behavior.
     512    * Validates that the given value is a valid e-mail address, using a
    486513      moderately complex regular expression.
    487514    * Error message keys: ``required``, ``invalid``
    488515
    Takes two optional arguments for validation:  
    618645
    619646    * Default widget: ``TextInput``
    620647    * Empty value: ``''`` (an empty string)
    621     * Normalizes to: A Unicode object.
     648    * Normalizes to: A Unicode object with stripped leading and trailinig whitespace.
     649      Set ``normalize=False`` to disable stripping spaces or set
     650      ``normilize=your_callable_name`` to change normalization behavior.
    622651    * Validates that the given value is a valid IPv4 address, using a regular
    623652      expression.
    624653    * Error message keys: ``required``, ``invalid``
    and the error message as the value.  
    746775
    747776   * Default widget: ``TextInput``
    748777   * Empty value: ``''`` (an empty string)
    749    * Normalizes to: A Unicode object.
     778    * Normalizes to: A Unicode object with stripped leading and trailinig whitespace.
     779      Set ``normalize=False`` to disable stripping spaces or set
     780      ``normilize=your_callable_name`` to change normalization behavior.
    750781   * Validates that the given value contains only letters, numbers,
    751782     underscores, and hyphens.
    752783   * Error messages: ``required``, ``invalid``
    If no ``input_formats`` argument is provided, the default input formats are::  
    785816
    786817    * Default widget: ``TextInput``
    787818    * Empty value: ``''`` (an empty string)
    788     * Normalizes to: A Unicode object.
     819    * Normalizes to: A Unicode object with stripped leading and trailinig whitespace.
     820      Set ``normalize=False`` to disable stripping spaces or set
     821      ``normilize=your_callable_name`` to change normalization behavior.
    789822    * Validates that the given value is a valid URL.
    790823    * Error message keys: ``required``, ``invalid``, ``invalid_link``
    791824
  • tests/regressiontests/forms/tests/fields.py

    diff --git a/tests/regressiontests/forms/tests/fields.py b/tests/regressiontests/forms/tests/fields.py
    index 6780413..1dcff0d 100644
    a b class FieldsTests(TestCase):  
    131131        self.assertEqual(f.max_length, None)
    132132        self.assertEqual(f.min_length, 10)
    133133
     134    def test_charfield_normalize(self):
     135        f = CharField()
     136        self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, "  \t")
     137
     138    def test_charfield_normalize_false(self):
     139        f = CharField(normalize=False)
     140        self.assertEqual("  \t", f.clean("  \t"))
     141
    134142    # IntegerField ################################################################
    135143
    136144    def test_integerfield_1(self):
Back to Top