2013-05-19 74 views
0

如何在模型clean方法中提高ValidationException提高模型清潔方法中的字段錯誤

def clean(self): 
    from django.core.exceptions import ValidationError 
    raise ValidationError({'title': 'not ok'}) 

上面(使用形式時)未在錯誤添加到title領域,但對非字段的錯誤。

我知道怎麼做了一個表格(self._errors['title'] = self.error_class([msg]))內,但self._errors不車型內部存在clean方法。

回答

2

你不這樣做,Model的清潔方法僅用於提高non field errors,但是你可以通過創建一個clean_title方法來引起一個現場錯誤。

def clean(self): 
    """ 
    Hook for doing any extra model-wide validation after clean() has been 
    called on every field by self.clean_fields. Any ValidationError raised 
    by this method will not be associated with a particular field; it will 
    have a special-case association with the field defined by NON_FIELD_ERRORS. 
    """ 
+0

是的,我也試過。但它似乎必須使用'validators = [clean_title]'來連接字段本身,因此'clean_title'必須在字段之前定義(或必須導入)。不是很方便。 – Zardoz