On Dec 19 2007, 5:41 pm, Andrew <[EMAIL PROTECTED]> wrote:
> This is code that was working until sometime circa rev 6500...
>
> Assuming we have a newform object named form with errors in it:
>
> import django.utils.simplejson as json
> json.dumps(form.errors)
>
> gives:
> <type 'exceptions.TypeError'>: <django.utils.functional.__proxy__
> object at 0x128f110> is not JSON serializable
>
> In the shell, and fails silently in view code.
>
> If we do:
>
> json.dumps(force_unicode(form.errors))
>
> the serialization will work, but returns pythonic representations of
> unicode strings (u'foo'), which the JS frontend has no idea how to
> handle.
>
> All I want to do is serialize the form's errors as a dictionary... I'm
> guessing this should be easy?

I just ran into this problem.  In my use case, I'm trying to dump form
errors to JSON in a view response, allowing client side javascript to
process the form errors.  I hit the same problem the OP hit, where the
serialization code errors out on the __proxy__ class constructed by a
call to lazy() (from functional.py).

In a nutshell, the validation error strings in newforms.fields.py are
wrapped in ugettext_lazy, which is just lazy(ugettext, unicode),
defined in translation.__init__.py.  So that's the culprit.

To get around the problem it seems can force the lazy function to
evaluate by casting to unicode.  E.g.,

>>> [str(e) for e in field.errors]
>>> ['<django.utils.functional.__proxy__ object at 0xba9790>']
str(e) doesn't work.

>>> [unicode(e) for e in field.errors]
>>> [u'This field is required.']
but unicode(e) does.

I'm not sure why this is as I'm a little fuzzy on the lazy evaluators,
but my rough understanding is that unless you ask for it in unicode,
you're not going to get it, you'll get the proxy.


Back to Andrew and my original problem getting the errors serialized
to json, here's what I did:

errors = {}
for field in form:
    errors[field.auto_id] = {'errors': [unicode(e) for e in
field.errors]}

simplejson.dumps(errors)


Doug Van Horn
www.maydigital.com
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to