在 JSON 中返回纯 Django 表单错误 [英] Returning pure Django form errors in JSON

查看:23
本文介绍了在 JSON 中返回纯 Django 表单错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Django 表单,我正在一个普通的 Django 视图中验证它.我想弄清楚如何提取纯错误(没有 HTML 格式).下面是我目前使用的代码.

I have a Django form which I'm validating in a normal Django view. I'm trying to figure out how to extract the pure errors (without the HTML formatting). Below is the code I'm using at the moment.

return json_response({ 'success' : False,
                       'errors' : form.errors })

这样,我从 Django 得到了臭名昭著的代理对象错误.将每个错误强制转换为 Unicode 也无济于事,因为这样每个错误的 __unicode__ 方法都会被有效地调用 HTML 化.

With this, I get the infamous proxy object error from Django. Forcing each error into Unicode won't do the trick either, because then each of the errors' __unicode__ method will be called effectively HTML-izing it.

有什么想法吗?

对于那些感兴趣的人,这是json_response的定义:

For those interested, this is the definition of json_response:

def json_response(x):
    import json
    return HttpResponse(json.dumps(x, sort_keys=True, indent=2),
                        content_type='application/json; charset=UTF-8')

推荐答案

经过 很多 折腾,测试不同的东西后得到了它.注意我不确定这是否也适用于国际化.这也需要每个字段的第一个验证错误,但修改它以获取所有错误应该相当容易.

Got it after a lot of messing around, testing different things. N.B. I'm not sure whether this works with internationalization as well. This also takes the first validation error for each field, but modifying it to get all of the errors should be rather easy.

return json_response({ 'success' : False,
                       'errors' : [(k, v[0].__unicode__()) for k, v in form.errors.items()] })

这篇关于在 JSON 中返回纯 Django 表单错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆