2

I am using

rf['email'].errors

As said in docs, I can use it to have array of errors.

[str(e) for e in rf['email'].errors]  #give me ["<django.utils.functional.__proxy__>"]

If repr or str - it gives ul's or string of array.

So it worked only when I used repr and eval together. But I think its stupid solution.

eval(`rf['email'].errors`)
2
  • Just a couple clarifications, if you don't mind: 1) Is rf a django Form? And rf['email'] a django FormField? 2) What is the output you're trying to get? Is it the HTML string for the errors? Or something else? Commented May 7, 2009 at 18:17
  • 1. rf is Form; 2. rf['email'] is FormField; 3. I am trying to achieve json. I use forms for validation. Commented May 7, 2009 at 18:20

1 Answer 1

2

You have a couple options depending on the output you'd like.

Option one, use the unicode constructor to convert the data:

list_of_error_texts = [unicode(e) for e in rf['email'].errors]

(Django's proxy object implements a method that responds to unicode.)

Option two, get the ErrorList as text. This produces a newline separated list of error text, with each line preceded by an asterisk:

print rf['email'].errors.as_text()
* My error one
* My error two

Option three, use django's force_unicode function. This is like unicode, but has some extra safety features:

from django.utils.encoding import force_unicode
list_of_error_texts = [force_unicode(e) for e in rf['email'].errors]
Sign up to request clarification or add additional context in comments.

2 Comments

Do you have any idea why the behavior explained in the docs doesn't work and we have to do like you did?
The docs promise that you can loop over the field errors, but the only examples in the docs (AFAICT) are in templates, not in python as the OP as written. When looping over the ErrorList that comes back from rf['email'], you get a series of ValidationError objects. Django's template infrastructure calls force_unicode() on them, which first checks if they have a 'unicode' method. Since they do, that's invoked, rather than the str() of the OP's example. So I wouldn't say the behaviour in the docs doesn't work, just that the examples don't include the OP's scenario :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.