I have a validation check on a form which depends on more than one field, but it would be good to have the validation error show the user specifically which fields are causing the issue, rather than just an error message at the top of the form. (the form has many fields so it would be clearer to show specifically where the error is).
As a work around I tried to create the same validation in each of the relevant fields clean_field()
method so the user would see the error next to those fields. However I only seem to be able to access that particular field from self.cleaned_data
and not any other?
Alternatively is it possible to raise a field error from the forms clean()
method?
Attempt 1:
def clean_supply_months(self):
if not self.cleaned_data.get('same_address') and not self.cleaned_data.get('supply_months'):
raise forms.ValidationError('Please specify time at address if less than 3 years.')
def clean_supply_years(self):
if not self.cleaned_data.get('same_address') and not self.cleaned_data.get('supply_years'):
raise forms.ValidationError('Please specify time at address if less than 3 years.')
def clean_same_address(self):
.....
If you want to access cleaned data for more than one field, you should use the clean
method instead of clean_<field>
method. The add_error()
method allows you to assign an error to a particular field.
For example, to add the Please specify time at address error message to the same_address
field, you would do:
def clean(self):
cleaned_data = super(ContactForm, self).clean()
if not self.cleaned_data.get('same_address') and not self.cleaned_data.get('supply_months'):
self.add_error('same_address', "Please specify time at address if less than 3 years.")
return cleaned_data
See the docs on validating fields that rely on each other for more info.
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