Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to raise multiple ValidationError on Django?

from rest_framework.exceptions import ValidationError

def to_representation(self, request_data):
    raise ValidationError({
        'field_name': ["Field not allowed to change"]
    })

In the example above how can I throw multiple validation errors? I want to throw them as dicts to show at the respective fields.

like image 403
Julio Marins Avatar asked Mar 12 '18 01:03

Julio Marins


2 Answers

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)
like image 132
friedteeth Avatar answered Oct 17 '22 18:10

friedteeth


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'),
])
like image 38
andilabs Avatar answered Oct 17 '22 17:10

andilabs