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?
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.
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With