[Fixed]-Django: overriding Model.validate_unique

24👍

Django expects your ValidationErrors to be instantiated with a dictionary instead of a string:

from django.db.models import Model
from django.core.exceptions import ValidationError
from django.core.exceptions import NON_FIELD_ERRORS


class Person(Model):

    ...

    def validate_unique(self, *args, **kwargs):
        super(Person, self).validate_unique(*args, **kwargs)
        if not self.id:
            if self.__class__.objects.filter(...).exists():
                raise ValidationError(
                    {
                        NON_FIELD_ERRORS: [
                            'Person with same ... already exists.',
                        ],
                    }
                )
👤Jian

Leave a comment