Java Jester

Elegant custom validation in django

At the time of this writing, the official django documentation doesn't teach an elegant way to handle custom form validation. After digging the django source code for a couple of minutes, I learned that I can place custom field validation on form class by defining a method named 'clean_<field_name>(self)'. In my example below, I'm adding custom fields that need to be validated against the database because I don't want any registration using the same email address. The following code shows how to do this:



class RegistrationForm(forms.ModelForm):

gender = forms.ChoiceField(required=True, widget=forms.RadioSelect, choices=GENDER)
    agree_to_terms = forms.BooleanField(required=True, help_text='You must agree to terms and conditions') 
    email = forms.EmailField(required=True)
    password = forms.CharField(required=True, widget=forms.PasswordInput())
    password2 = forms.CharField(required=True, label='Re-enter password')

def clean_email(self):
    email = self.cleaned_data["email"]
    try:
        User.objects.get(email=email)
    except
        User.DoesNotExist: return email raise forms.ValidationError('This email address is already taken.')

def clean_password2(self):
    password = self.cleaned_data["password"]
    password2 = self.cleaned_data["password2"]
    if password == password2:
        return password2
    raise forms.ValidationError('Confirmation password should be equal to the password')

class Meta:
    model = UserProfile
    exclude = ('user', 'is_activated', 'activation_key', )

 

Comments (0)


recommended books
Jester Cap Logo by Vonn reyjexter.com | Valid XHTML & CSS | 2008 | Design & Devt. by: vonnhugo

powered by:

django framework python google app engine