在JSON中返回纯Django表单错误 [英] Returning pure Django form errors in JSON
问题描述
return json_response({'success':False,
'errors':form.errors})
有了这个,我从Django得到臭名昭着的代理对象错误。将每个错误强制为Unicode也不会这样做,因为每个错误' __ unicode __
方法将被有效地称为HTML。
任何想法?
编辑:
对于那些感兴趣的人,定义 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')
在em不同的东西。注:我不知道这是否与国际化有关。这也是每个字段的第一个验证错误,但修改它以获取所有错误应该是相当容易的。
返回json_response({'success':False,
'errors':[(k,v [0] .__ unicode __())for k,v in form.errors.items()]})
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 })
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.
Any ideas?
EDIT:
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屋!