[Django]-Django – Keeping the original method's work and add new custom validation

5πŸ‘

βœ…

Call the super classes clean method:

def clean(self): 
    super(MyUserAdminForm, self).clean()
    # more cleaning

This is a common python thing to do when you subclass something and redefine functionaly but want to make sure you keep the super class functionality. Extremely common when you do an init method, as you always need to ensure the super class constructor gets called to set up the instance.

πŸ‘€jdi

0πŸ‘

class ContactForm(forms.Form):
        message = forms.CharField()
        def clean_message(self):
                num_words = len(message.split())
                if num_words<4:
                        raise forms.ValidationError("Too short a message!")
                return message 

This is the way you add a validation method on a field, and this does ensure that the default cleanup happens. There is no need to call the default cleanup method again.

Source: www.djangobook.com

How it works:

When is_valid() is called on the form object, the system looks for any methods in the class that begin with clean_ and ends with an attribute name. If they do, it runs them after running the default cleanup methods.

πŸ‘€SiddharthaRT

Leave a comment