How to json serialize form errors in Django

This is really ugly and you will absolutely need it if you’d like to json serialize form errors in Django. Why? Because you’d like to reply to an AJAX request and just pass trough the errors your form has generated.

simplejson itself is not able to serialize the ErrorDict. But not the ErrorDict itself is the problem - the proxy objects within the ErrorDict are the problem. Those proxy objects represent a string (unicode here) and will be casted whenever needed. This ensures that you won’t run into problems with internationalization.

Russell Keith-Magee posted an excellent explanation on a topic dealing with this in ‘django users’ group.
Also the solution can be found there. I just had to stuff it into a function and now my forms generate error messages that can be understood by e.g. a GWT client.

def error_form_serialization(error_dict):  
    This method strips the proxy objects from the
    error dict and casts them to unicode. After
    that the error dict can and will be
    plain_dict = dict([(k, [unicode(e) for e in v]) for k,v in error_dict.items()])   
    return simplejson.dumps(plain_dict)