Newforms customs validators

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. boostrap prepend-input for widgets by DimmuR 7 months, 3 weeks ago
  2. boostrap append-input for widgets by DimmuR 7 months, 3 weeks ago
  3. CodeLookupField by girasquid 3 years, 11 months ago
  4. use oldforms validators in newforms forms by garywilson 6 years, 1 month ago
  5. Modifying the fields of a third/existing model class by marinho 2 years, 4 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,
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.

#

(Forgotten your password?)