Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django form - raising specific field validation error from clean()

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):
          .....
like image 980
Yunti Avatar asked Nov 30 '17 13:11

Yunti


1 Answers

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.

like image 173
Alasdair Avatar answered Sep 22 '22 01:09

Alasdair