user1102018
user1102018

Reputation: 4451

Django how to override clean() method in a subclass of custom form?

I created a custom form with custom validation like this:

class MyCustomForm(forms.Form):
    # ... form fields here

    def clean(self):
        cleaned_data = self.cleaned_data
        # ... do some cross-fields validation here

        return cleaned_data

Now, this form is subclassed with another form which has its own clean method.
What is the correct way to trigger both clean() methods?
At the moment, this is what I do:

class SubClassForm(MyCustomForm):
    # ... additional form fields here

    def clean(self):
        cleaned_data = self.cleaned_data
        # ... do some cross-fields validation for the subclass here

        # Then call the clean() method of the super  class
        super(SubClassForm, self).clean()

        # Finally, return the cleaned_data
        return cleaned_data

It seems to work. However, this makes two clean() methods return cleaned_data which seems to me a bit odd.
Is this the correct way?

Upvotes: 20

Views: 31033

Answers (1)

Mounir
Mounir

Reputation: 11746

You do it well, but you should load cleaned_data from super call like this:

class SubClassForm(MyCustomForm):
        # ... additional form fields here

    def clean(self):
        # Then call the clean() method of the super  class
        cleaned_data = super(SubClassForm, self).clean()
        # ... do some cross-fields validation for the subclass 

        # Finally, return the cleaned_data
        return cleaned_data

Upvotes: 28

Related Questions