Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject errors into already validated form?

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.

like image 354
Parand Avatar asked Oct 09 '08 19:10

Parand


People also ask

How do you show error messages on a form?

In order to display error messages on forms, you need to consider the following four basic rules: The error message needs to be short and meaningful. The placement of the message needs to be associated with the field. The message style needs to be separated from the style of the field labels and instructions.

What happens once validation is complete?

After submit validationThe response of the “validator” is sent back to the user's computer and it's visualized as either a confirmation message (“everything went fine!”) or a set of error messages.” In other words, you fill out the whole form and then press submit.


2 Answers

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

like image 63
rstuart85 Avatar answered Sep 19 '22 21:09

rstuart85


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

like image 23
John Millikin Avatar answered Sep 20 '22 21:09

John Millikin