模型清理法中提高场误差

2024-09-27 00:22:16 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在django的modelsclean方法中引发字段绑定ValidationException?在

from django.core.exceptions import ValidationError

def clean(self):
    if self.title:
        raise ValidationError({'title': 'not ok'})

上面的操作不会将错误添加到title字段(使用表单时),而是添加到非字段错误(__all__)。在

我知道如何在表单(self._errors['title'] = self.error_class([msg]))内完成,但是在modelsclean方法中,self._errors不存在。在


Tags: django方法fromcoreimportself表单title
2条回答

不需要,Model的clean方法只用于引发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.
    """

根据Django文档,使用 model.clean()

这提供了你所要求的一切!在

注释上方的框似乎是您要查找的内容:

raise ValidationError({
    'title': ValidationError(_('Missing title.'), code='required'),
    'pub_date': ValidationError(_('Invalid date.'), code='invalid'),
})

code参数是kwarg,因此是可选的。(它在示例中,所以我粘贴在上面)

我猜你需要这样的东西:

^{pr2}$

相关问题 更多 >

    热门问题