在我的 form.Form验证用户输入值之后,我将它们传递给一个单独的(外部)进程进行进一步处理。这个外部过程可能会在值中发现更多的错误。
form.Form
有没有一种方法可以将这些错误注入到已经验证的表单中,以便通过常用的表单错误显示方法(或者有更好的替代方法)来显示它们?
一个建议是在表单验证中包含外部处理,这并不理想,因为外部处理不仅仅是验证。
You can add additional error details to the form's _errors attribute directly:
_errors
https://docs.djangoproject.com/en/1.5/ref/forms/validation/#described-later https://docs.djangoproject.com/en/1.6/ref/forms/validation/#modifying-field-errors
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:
Form._errors
ErrorList
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".
django.forms.forms.NON_FIELD_ERRORS
"__all__"
"myfield"
For Django 1.7+, you should use form.add_error() instead of accessing form._errors directly.
form.add_error()
form._errors
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