Login

Newforms customs validators

Author:
baptiste
Posted:
March 18, 2007
Language:
Python
Version:
Pre .96
Score:
0 (after 2 ratings)

How to proceed to add a custom validator to a newforms field : you just need to create a new class derivated from forms.YourField with a custom clean method. Do not forget the line super(UserField, self).clean(value) ; in our case, it verifies the field attributes : min_length, max_length or required.

More explications (in French) : des validateurs personnalisés pour Django

1
2
3
4
5
6
7
8
class UserField(forms.CharField):
    def clean(self, value):
        super(UserField, self).clean(value)
        try:
            User.objects.get(username=value)
            raise forms.ValidationError("Someone is already using this username. Please pick an other.")
        except User.DoesNotExist:
            return value

More like this

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

Comments

richardbarran (on March 22, 2007):

Hi,

This snippet contains a small bug, line 3 should be:

value = super(UserField, self).clean(value)

Reason:

The 'clean' method of the parent class - forms.Charfield - returns 'value' converted to a unicode string, however in the snippet this return value is ignored.

HTH,<br /> Richard

PS It took me a while to understand why é and ô's were causing me a problem :-)

#

rahmcoff (on March 9, 2008):

Lines 6 and 7 should be swapped, and line 8 should be un-indented a level.

#

Please login first before commenting.