I need to overwrite the clean()
method in a Django Model form to perform additional uniqueness checks on the data entered.
This page gives implementation details: https://docs.djangoproject.com/en/1.11/ref/forms/validation/ Copied here:
def clean(self):
cleaned_data = super(ContactForm, self).clean()
cc_myself = cleaned_data.get("cc_myself")
subject = cleaned_data.get("subject")
if cc_myself and subject:
# Only do something if both fields are valid so far.
if "help" not in subject:
raise forms.ValidationError(
"Did not send for 'help' in the subject despite "
"CC'ing yourself."
)
However I'm confused why this method doesn't return cleaned_data
at the end of the function? Surely that is the correct thing to do?
Have a look at django's _clean_form
method:
def _clean_form(self):
try:
cleaned_data = self.clean()
except ValidationError as e:
self.add_error(None, e)
else:
if cleaned_data is not None:
self.cleaned_data = cleaned_data
Read the last bullet point on the forms doc and especially this bit of the ModelForm doc.
If the clean
method raises a ValidationError
, the error gets added to the forms' errors.
If the clean
method has returned anything and threw no errors, the form is going to use that for its cleaned_data
attribute. Otherwise it will keep its 'old' one.
In your case, all that your clean
method does, is validating an aspect of the form.
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