Inject errors into already validated form?

DjangoDjango Forms

Django Problem Overview


After my form.Form validates the user input values I pass them to a separate (external) process for further processing. This external process can potentially find further errors in the values.

Is there a way to inject these errors into the already validated form so they can be displayed via the usual form error display methods (or are there better alternative approaches)?

One suggestions was to include the external processing in the form validation, which is not ideal because the external process does a lot more than merely validate.

Django Solutions


Solution 1 - Django

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

Solution 2 - Django

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".

Solution 3 - Django

Solution 4 - Django

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionParandView Question on Stackoverflow
Solution 1 - Djangorstuart85View Answer on Stackoverflow
Solution 2 - DjangoJohn MillikinView Answer on Stackoverflow
Solution 3 - DjangoJonny BuchananView Answer on Stackoverflow
Solution 4 - DjangoMuhammad Faizan FareedView Answer on Stackoverflow