Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 455
user1102018 Avatar asked Apr 26 '13 07:04

user1102018


People also ask

What does super () clean () do in Django?

The call to super(). clean() in the example code ensures that any validation logic in parent classes is maintained. If your form inherits another that doesn't return a cleaned_data dictionary in its clean() method (doing so is optional), then don't assign cleaned_data to the result of the super() call and use self.

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

How do you remove this field is required Django?

If yes try to disable this behavior, set the novalidate attribute on the form tag As <form action="{% url 'new_page' %}", method="POST" novalidate> in your html file.

What is ModelForm in Django?

Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.


1 Answers

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
like image 140
Mounir Avatar answered Oct 29 '22 23:10

Mounir