form.errors is not a dictionary?

1,117 views
Skip to first unread message

Roy Smith

unread,
Apr 5, 2011, 4:43:48 PM4/5/11
to Django users
I'm using django-1.3 . I have a view with the following code:

def item_create(request):
if request.method == 'POST':
form = ItemForm(request.POST)
if form.is_valid():
url = form.cleaned_data['url']
item.save()
return HttpResponseRedirect('/')
else:
print form.errors

when I submit the form, I expected that form.errors would print out as
a dict, as documented in http://docs.djangoproject.com/en/1.3/ref/forms/api/#using-forms-to-validate-data.
Instead, I'm getting a hunk of HTML:


Django version 1.3, using settings 'soco-site.settings'
Development server is running at http://0.0.0.0:7626/
Quit the server with CONTROL-C.
<ul class="errorlist"><li>date_added<ul class="errorlist"><li>This
field is required.</li></ul></li><li>user_id<ul
class="errorlist"><li>This field is required.</li></ul></li></ul>
[05/Apr/2011 16:36:32] "POST /item/create/ HTTP/1.1" 200 718

Is my understanding wrong, or is this a bug?

Daniel Roseman

unread,
Apr 5, 2011, 6:01:14 PM4/5/11
to django...@googlegroups.com
To coin a phrase, it's not a bug - it's a feature.

form.errors is actually an instance of a custom class, ErrorDict, which is defined in django.forms.util. It subclasses dict, so it works exactly the same as a dictionary when you set and access its members - but it also defines a custom __unicode__ method, which is called automatically when you `print` it, which converts the contents to HTML. This is so you get a nicely-formatted output in your template.
--
DR.

Victor Rocha

unread,
Aug 1, 2012, 10:52:17 AM8/1/12
to django...@googlegroups.com
Read the above reply.

When you print form.error --> prints out a custom __unicode__ for you to use in your templates.
However, you can iterate over form.errors and it will act as a normal dict.



On Wednesday, August 1, 2012 1:56:28 AM UTC-4, vivek soundrapandi wrote:
I too have the same problem. How did you fix it?
Reply all
Reply to author
Forward
0 new messages