6

如何ValidationException在 django 的模型clean方法中提高字段绑定?

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])) 中执行此操作,但在模型方法self._errors中不存在。clean

4

2 回答 2

9

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

这提供了您所要求的一切!

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

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

code 参数是一个 kwarg,因此是可选的。(它在示例中,所以我已将其粘贴过来)

在你的情况下,我的猜测是你需要这样的东西:

raise ValidationError({
    'title': ValidationError('not ok'),
})
于 2018-03-26T07:25:14.663 回答
2

你没有,aModel的 clean 方法仅用于non field errorsraise ,但是你可以通过创建一个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.
    """
于 2013-05-19T11:41:33.793 回答