2012-12-28 39 views
10

重寫Django的Model.validate_unique的正確方法是什麼?我試圖重寫它,提高我自己的ValidationError,但得到這個錯誤:Django:重寫Model.validate_unique

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

回答

21

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