Jian
Jian

Reputation: 11070

Django: overriding Model.validate_unique

What is the right way to override Django's Model.validate_unique? I tried overriding it and raising my own ValidationError, but got this error:

AttributeError: 'ValidationError' object has no attribute 'message_dict'

Upvotes: 13

Views: 5953

Answers (1)

Jian
Jian

Reputation: 11070

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.',
                        ],
                    }
                )

Upvotes: 24

Related Questions