在 JSON 中返回纯 Django 表单错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/986406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning pure Django form errors in JSON
提问by Deniz Dogan
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.
我有一个 Django 表单,我正在一个普通的 Django 视图中验证它。我想弄清楚如何提取纯错误(没有 HTML 格式)。下面是我目前使用的代码。
return json_response({ 'success' : False,
'errors' : form.errors })
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.
有了这个,我从 Django 得到了臭名昭著的代理对象错误。将每个错误强制转换为 Unicode 也不会__unicode__奏效,因为这样每个错误的方法都将被有效地调用 HTML 化。
Any ideas?
有任何想法吗?
EDIT:
编辑:
For those interested, this is the definition of json_response:
对于那些感兴趣的人,这是 的定义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')
采纳答案by Deniz Dogan
Got it after a lotof 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()] })
回答by SystemParadox
This appears to have been improved. The following works in Django 1.3:
这似乎得到了改善。以下在 Django 1.3 中有效:
return json_response({
'success': False,
'errors': dict(form.errors.items()),
})
No need for __unicode__or lazy translation any more. This also gives a full array of errors for each field.
不再需要__unicode__或懒惰的翻译。这也为每个字段提供了完整的错误数组。
回答by lampslave
For Django 1.7+ use Form.errors.as_json()or something like this:
对于 Django 1.7+ 使用Form.errors.as_json()或类似的东西:
errors = {f: e.get_json_data() for f, e in form.errors.items()}
return json_response(success=False, data=errors)
回答by Arthur Debert
回答by 0077cc
We can do this:
我们可以完成这个:
import simplejson as json
errors = json.dumps(form.errors)
return HttpResponse(errors, mimetype='application/json')
回答by bjunix
json.dumpscan't serialize django's proxy function (like lazy translations).
json.dumps无法序列化 django 的代理功能(如惰性翻译)。
As documentedyou should create a new Encoder class:
如文档所述,您应该创建一个新的 Encoder 类:
import json
from django.utils.functional import Promise
from django.utils.encoding import force_text
from django.core.serializers.json import DjangoJSONEncoder
class LazyEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, Promise):
return force_text(obj)
return super(LazyEncoder, self).default(obj)
Use the new Encoder like this:
像这样使用新的编码器:
json.dumps(s, cls=LazyEncoder)
That's all :)
就这样 :)

