dabadaba
dabadaba

Reputation: 9512

How to raise multiple non-field errors

The clean method is the place to raise non-field errors:

def clean(self):
   cleaned_data = super(MyForm, self).clean()
   if condition1(cleaned_data['f1'], cleaned_data['f2']):
       raise ValidationError('Condition1 error')

   if condition3(cleaned_data['f3'], cleaned_data['f4']):
       raise ValidationError('Condition2 error')

But what if I want to raise both so that the user sees all errors at once instead of having to correct them one by one?

This is possible with field errors passing a dictionary to ValidationError, but what about non-field errors?

Upvotes: 1

Views: 1204

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599450

You can use the Form add_error method to do this:

if condition1(cleaned_data['f1'], cleaned_data['f2']):
   self.add_error(None, ValidationError('Condition1 error'))

if condition3(cleaned_data['f3'], cleaned_data['f4']):
   self.add_error(None, ValidationError('Condition2 error'))

Upvotes: 3

Related Questions