Wednesday, July 25, 2012

Django clean(), non-field-errors, and ValidationError(['can','put','a','list here',]

adding more than one error to non_field_errors - Google Search

http://stackoverflow.com/questions/8598247/how-to-append-error-message-to-form-non-field-errors-in-django


  1. Call full_clean(), this should initialize form._errors. This step is critical, if you don't do it, it won't work.
  2. Make the error list, it takes a list of messages, instanciate it as such: error_list = form.error_class(['your error messages'])
  3. Assign the error list to NON_FIELD_ERRORS, you have to import NON_FIELD_ERRORS fromdjango.forms.forms, then assign as such: form._errors[NON_FIELD_ERRORS] = error_list
Here is a demonstration from a shell:
In [1]: from bet.forms import BetForm
In [2]: from django.forms.forms import NON_FIELD_ERRORS
In [3]: form = BetForm()
In [4]: form.full_clean()
In [5]: form._errors[NON_FIELD_ERRORS] = form.error_class(['your error messages'])
In [6]: form.non_field_errors()
Out[6]: [u'your error messages']





2
Adding non-field-error(s) from the view.
http://stackoverflow.com/questions/4229024/django-add-non-field-error-from-view


I've got a Django form with a bunch of fields that I'm rendering in the template. I've also got some straight HTML input elements which I want to validate in the view by accessing the request.POST vars. If those don't validate, I want to inject an error into the Django form so I can display it on the page. Is there a way to do that?
Adding to Daniel's answer, the specific syntax is:
form.errors['__all__'] = form.error_class(["error msg"])









3
You can pass in a list to ValidationError([,,,]). so that you will have a list of li in non-field-errors.


















No comments:

Post a Comment