[Fixed]-How to raise multiple ValidationError on Django?

23👍

You throw one ValidationError with multiple fields errors inside:

    raise ValidationError({
        'field_name_1': ["Field not allowed to change"],
        'field_name_2': ["Field not allowed to change"],
    })

Django 3.0+ style should follow docs:

raise ValidationError([
    ValidationError('Error 1', code='error1'),
    ValidationError('Error 2', code='error2'),
])

6👍

I do not recommend validating every single field inside only one function. What you should do instead is use one function to validate one field, it is way easier and simpler. If you want to do multiple validations you can find the documentation for handling multiple errors at link. The documentation shows the example below:

# Good
raise ValidationError([
    ValidationError(_('Error 1'), code='error1'),
    ValidationError(_('Error 2'), code='error2'),
])

# Bad
raise ValidationError([
    _('Error 1'),
    _('Error 2'),
])

And here is an example of mine:

def validate_field(value):
    errors = []

    if len(value) > 50:
        errors.append(ValidationError(
            'Error message'
        ))
    if not value.isalpha():
        errors.append(ValidationError(
            'Error message'
        ))

    if errors:
        raise ValidationError(errors)

0👍

If you’re talking about the django admin, you can also use add_error().

Docs: https://docs.djangoproject.com/en/4.1/ref/forms/api/#django.forms.Form.add_error

class DatForm(forms.ModelForm):
    def clean(self):
        cleaned_data = super().clean()
        age = cleaned_data.get('age')  # IntegerField on your model.
        mood = cleaned.data.get('mood')  # CharField on your model. 

        if age and age < 10:
           self.add_error('age', 'You must be at-least 10 years old!')
        if mood and mood.lower() != 'happy':
           self.add_error('mood', 'Why so serious?')

        return cleaned_data

This will raise all errors and at each field, rather than all at the top.
Tested with Django 4.0.4

Leave a comment