Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding errors to Django form errors.__all__

How do I add errors to the top of a form after I cleaned the data? I have an object that needs to make a REST call to an external app (google maps) as a pre-save condition, and this can fail, which means I need my users to correct the data in the form. So I clean the data and then try to save and add to the form errors if the save doesn't work:

if request.method == "POST":
#clean form data
    try:
        profile.save()
        return HttpResponseRedirect(reverse("some_page", args=[some.args]))
    except ValueError:
        our_form.errors.__all__ = [u"error message goes here"]
return render_to_response(template_name, {"ourform": our_form,}, 
       context_instance=RequestContext(request))

This failed to return the error text in my unit-tests (which were looking for it in {{form.non_field_errors}}), and then when I run it through the debugger, the errors had not been added to the forms error dict when they reach the render_to_response line, nor anywhere else in the our_form tree. Why didn't this work? How am I supposed to add errors to the top of a form after it's been cleaned?

like image 474
hendrixski Avatar asked Feb 10 '10 07:02

hendrixski


2 Answers

You really want to do this during form validation and raise a ValidationError from there... but if you're set on doing it this way you'll want to access _errors to add new messages. Try something like this:

from django.forms.util import ErrorList

our_form._errors["field_name"] = ErrorList([u"error message goes here"])
like image 94
Gabriel Hurley Avatar answered Sep 18 '22 07:09

Gabriel Hurley


Non field errors can be added using the constant NON_FIELD_ERRORS dictionary key (which is __all__ by default):

from django import forms
errors = my_form._errors.setdefault(forms.forms.NON_FIELD_ERRORS, forms.util.ErrorList())
errors.append("My error here")
like image 36
bmihelac Avatar answered Sep 18 '22 07:09

bmihelac