关于django form.errors的问题,以获取原始的错误消息 [英] Questions about django form.errors, to get the raw error messages
问题描述
django文件说
https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.errors
访问错误属性来获取错误消息的字典:
f.errors
{'sender':['输入有效的电子邮件地址'],'subject':['此字段是必需的。']}
但是,当我尝试打印forms.errors,我有html代码。
pre>
def login(request):
if request.method ==GET:
return render(request,rlogin.html)
else =
form = LoginForm(request.POST)
如果form.is_valid():
返回HttpResponse(valid)
else:
打印表单.errors
返回HttpResponse(Invalid)
code> Django版本1.6.4,使用设置'test_proj.settings'
启动开发服务器http://127.0.0.1:8000/
使用CTRL-BREAK退出服务器。
< ul class =errorlist>< li> username< ul class =errorlist>< li>确保此值ha
s最多3个字符具有6)。< / li>< / ul>< / li>< / ul>
我需要获取原始错误以显示ajax信息,例如
response_json = {status:error,content:用户名太短}
如果有任何其他方式获得原始错误消息,您也可以告诉我。谢谢!
这只是一个调用 print
的伪装:这意味着转换为一个字符串,而ErrorList类的 __ str __
方法调用其 as_ul
方法作为HTML输出 - 这样就可以通过执行 {{form.errors
对象本身的内容不在HTML中,您可以通过执行打印repr(form.errors)
。
The django document says https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.errors
Access the errors attribute to get a dictionary of error messages:
f.errors {'sender': ['Enter a valid email address.'], 'subject': ['This field is required.']}
However, when I try to print forms.errors, I got html code.
def login(request):
if request.method == "GET":
return render(request, r"login.html")
else:
form = LoginForm(request.POST)
if form.is_valid():
return HttpResponse("valid")
else:
print form.errors
return HttpResponse("Invalid")
Django version 1.6.4, using settings 'test_proj.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
<ul class="errorlist"><li>username<ul class="errorlist"><li>Ensure this value ha
s at most 3 characters (it has 6).</li></ul></li></ul>
I need to get the raw errors to show an ajax messager, for exemple
response_json = {"status": "error", "content": "Username is too short"}
If there is any other way to get the raw error messages, You can also tell me.Thanks!
That's simply an artefact of calling print
: that implictly converts to a string, and the ErrorList class's __str__
method calls its as_ul
method to output as HTML - this is so you can output the errorlist in a template simply by doing {{ form.errors }}
.
The contents of the object itself are not in HTML, and you can see it by doing print repr(form.errors)
.
这篇关于关于django form.errors的问题,以获取原始的错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!