Vivek S
Vivek S

Reputation: 5540

why is django form.errors displayed as string?

I am using a django form.I pass the form errors to template as,

return render_to_response(template_name, {'form':form})

In template i need to convert this to a js dictionary so i used,

eval({{form.errors|safe}})

but wherever i use form.errors in template i get the html format and not the dictionary. why is django forms getting displayed as a string rather than a dictionary. is there a way to use the dictionary version of form.errors.

Upvotes: 1

Views: 2980

Answers (2)

Filip Dupanović
Filip Dupanović

Reputation: 33660

It's getting displayed as an unordered list because the error collection's ErrorDict.__unicode__ method returns the value of ErrorDict.as_ul.

If you want to get back the default string representation of the dictionary, cast it back to a dictionary: dict(form.errors). Now you won't be getting an HTML formatted unordered list anymore.

Update

If your trying to represent a Python dictionary in JS, then keep it simple and encode the dictionary object to JSON. So somewhere in your view:

from django.utils import simplejson

errors = simplejson.dumps(form.errors)

Upvotes: 5

Jonas Geiregat
Jonas Geiregat

Reputation: 5432

Looking at django's source, errors should be of the type django.forms.util.ErrorDict.

Which has the following two methods that might be interesting for your case: as_text and as_ul.

I don't see how you could have used the eval method from within a django template. As far as I know that not even a valid standard django template tag.

I think you should manually loop over the dict and print/generate the javascript object literal accordingly.

Upvotes: 0

Related Questions