13

覆盖 Django 的 Model.validate_unique 的正确方法是什么?我尝试覆盖它并提高自己的ValidationError,但收到此错误:

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

1 回答 1

24

Django 期望您的 ValidationErrors 用字典而不是字符串来实例化:

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.',
                        ],
                    }
                )
于 2012-12-28T20:47:58.507 回答