Login

Automatic stripping textual form fields

Author:
nail.xx
Posted:
August 10, 2008
Language:
Python
Version:
.96
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': '  [email protected]  '})
>>> form.is_valid()
True
>>> form.cleaned_data
{'name': u'Victor', 'email': u'[email protected]'}

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

# min_length constraint is checked after strip, so it is imposible now to shut up validator with
# dummy spaces
>>> form = PersonForm({'name': '  E  ', 'email': '[email protected]'})
>>> 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': '[email protected]'})
>>> form.is_valid()
True

"""}

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

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.