在已经验证的表单中注入错误?

在我的 form.Form验证用户输入值之后,我将它们传递给一个单独的(外部)进程进行进一步处理。这个外部过程可能会在值中发现更多的错误。

有没有一种方法可以将这些错误注入到已经验证的表单中,以便通过常用的表单错误显示方法(或者有更好的替代方法)来显示它们?

一个建议是在表单验证中包含外部处理,这并不理想,因为外部处理不仅仅是验证。

43643 次浏览

Form._errors can be treated like a standard dictionary. It's considered good form to use the ErrorList class, and to append errors to the existing list:

from django.forms.utils import ErrorList
errors = form._errors.setdefault("myfield", ErrorList())
errors.append(u"My error here")

And if you want to add non-field errors, use django.forms.forms.NON_FIELD_ERRORS (defaults to "__all__") instead of "myfield".

For Django 1.7+, you should use form.add_error() instead of accessing form._errors directly.

Documentation: https://docs.djangoproject.com/en/stable/ref/forms/api/#django.forms.Form.add_error

Add error to specific field :

form.add_error('fieldName', 'error description')

**Add error to non fields **

form.add_error(None, 'error description')
#Only pass None instead of field name