Login

Automatic stripping textual form fields

Author:
nail.xx
Posted:
August 10, 2008
Language:
Python
Version:
.96
Tags:
newforms forms strip auto
Score:
4 (after 4 ratings)

Here is a class decorator that allows not to bother with stripping leading and trailing white space from user input provided via forms. This could be a temporary solution for an issue addressed in the ticket #6362.

The documentation is provided in the form of doctest. The decorator works with ModelForm's just as well as with ordinary forms.

Note however that this is not a 100% panacea. Your models still could become malformed if theirs data is obtained from another source, not forms.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from django import forms

def autostrip(cls):
    fields = [(key, value) for key, value in cls.base_fields.iteritems() if isinstance(value, forms.CharField)]
    for field_name, field_object in fields:
        def get_clean_func(original_clean):
            return lambda value: original_clean(value and value.strip())
        clean_func = get_clean_func(getattr(field_object, 'clean'))
        setattr(field_object, 'clean', clean_func)
    return cls

__test__ = {'USAGE': """

# Few lines to configure the test environment...
>>> from django.conf import settings
>>> settings.configure()

# Lets define a form that will be used for the test. Note last line of this block, thats how
# we apply ``autostrip`` decorator.
>>> class PersonForm(forms.Form):
...     name = forms.CharField(min_length=2, max_length=10)
...     email = forms.EmailField()
...     
...     def clean_name(self):
...         return self.cleaned_data['name'].capitalize()
>>> PersonForm = autostrip(PersonForm)

# Lets see how autostrip works against data with leading and trailing whitespace.
# Autostrip is performed on ``CharField``s and all its descendants such as ``EmailField``,
# ``URLField``, ``RegexField``, etc.
>>> form = PersonForm({'name': '  Victor  ', 'email': '  secret@example.ru  '})
>>> form.is_valid()
True
>>> form.cleaned_data
{'name': u'Victor', 'email': u'secret@example.ru'}

# ``clean_*`` methods works after stripping, so the letter and not the space is capitalized:
>>> form = PersonForm({'name': '  victor', 'email': 'zz@zz.zz'})
>>> form.is_valid()
True
>>> form.cleaned_data
{'name': u'Victor', 'email': u'zz@zz.zz'}

# min_length constraint is checked after strip, so it is imposible now to shut up validator with
# dummy spaces
>>> form = PersonForm({'name': '  E  ', 'email': 'zz@zz.zz'})
>>> form.is_valid()
False
>>> form.errors
{'name': [u'Ensure this value has at least 2 characters (it has 1).']}

# max_length constraint is checked after strip as well
>>> form = PersonForm({'name': '            Victor              ', 'email': 'zz@zz.zz'})
>>> form.is_valid()
True

"""}

if __name__ == "__main__":
    import doctest
    doctest.testmod()

More like this

  1. AjaxForm Base Classes by btaylordesign 4 years, 3 months ago
  2. Automatically strip CharFields by pietras 5 years, 11 months ago
  3. unique validation for ModelForm by whiskybar 7 years, 3 months ago
  4. ModelForm Class saving m2m by ckarrie2 3 years, 9 months ago
  5. remove the annoying "Hold down control..." messages by arthur 4 years, 3 months ago

Comments

Please login first before commenting.