Django--form验证及错误处理
需求
from表单验证和ajax验证时返回的错误信息处理
速查
1、form表单提交时错误信息显示
views
1 2 | error = form表单实例化对象.errorsreturn render(request,'前端html',{'obj':form表单实例化对象,'error':error}) #传到前端用simple_tag解析 |
html
1 2 | {% load xx %} <!--导入自定义sample_tag语言文件--><span>{% error_msg error.username %}</span> <!--error.username当做参数传给error_msg函数,并获取返回值--> |
simple_tag
1 2 3 4 5 | @register.simple_tagdef error_msg(error_list): if error_list: return error_list[0] return '' |
2、ajax提交时错误信息返回
views
1 2 | error = obj.errors.as_json()return HttpResponse(error) |
html
1 2 3 4 5 6 | $.ajax({ success: function(arg){ //arg是返回值,必须是字符串 var callback_dict = $.parseJSON(arg); $('#uname_error').text(callback_dict.username[0].message); } }) |
知识点
obj=表单生成文件.表单创建的类(request.POST)
request.POST:所有提交信息
obj.is_valid():判断提交数据是否正确
obj.clean():获取提交的所有数据
obj.errors():获取提交的所有错误信息,有三种表示方式(as_ul、as_json、as_data):
form表单提交用默认的,type<class django.forms.utils.ErrorDict>
ajax返回信息用as_json(),type<'str'>
错误信息里包含的字段和form里的字段一样,错误是个列表,取值obj.errors['username'][0]
html中jinja2语法取字典是不能用errors['key']的方式,得用errors.key;如果获取obj.errors['username'][0],就得用sample_tag
详细
1、form表单提交时错误信息显示
app01/views/account.py
1 2 3 4 5 6 7 8 9 10 11 | from app01.forms import account as AccountFormdef login(request): obj = AccountForm.LoginForm(request.POST) if request.method=='POST': if obj.is_valid(): all_data = obj.clean() else: error = obj.errors return render(request,'account/login.html',{'obj':obj,'error':error}) return render(request,'account/login.html',{'obj':obj}) |
为什么使用sample_tag去取值,而不取好了再传到html,因为如果字段很多的话,要分别定义每个的错误;
templates/login.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | {% load xx %} <!--导入自定义sample_tag语言文件--><html lang="en"><head></head><body> <form action="/login/" method="post"> <p> {{ obj.username }} <span>{% error_msg error.username %}</span> <!--error.username当做参数传给error_msg函数,并获取返回值--> </p> <p> {{ obj.password }}<span>{% error_msg error.password %}</span> </p> <input type="submit" value="submit" /> </form></body></html> |
app01/templatetags/xx.py
1 2 3 4 5 6 7 8 9 10 | from django import templatefrom django.utils.safestring import mark_safefrom django.template.base import resolve_variable, Node, TemplateSyntaxErrorregister = template.Library()@register.simple_tagdef error_msg(error_list): if error_list: return error_list[0] |
browser

2、ajax提交时错误信息返回
ajax必须返回的是字符串,所以用as_json()格式。
先看as_json获取的信息格式
1 2 3 4 5 6 7 8 | { "username": [ {"message": "This field is required.", "code": "required"} ], "password": [ {"message": "This field is required.", "code": "required"} ]} |
app01/views/account.py
1 2 3 4 5 6 7 8 9 10 11 | from app01.forms import account as AccountFormdef login(request): obj = AccountForm.LoginForm(request.POST) if request.method=='POST': if obj.is_valid(): all_data = obj.clean() else: error = obj.errors.as_json() return HttpResponse(error) return render(request,'account/login.html',{'obj':obj}) |
templates/login.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <form action="/login/" method="post"> <p> {{ obj.username }} <span id="uname_error"></span> </p> <p> {{ obj.password }} <span id="pwd_error"></span> </p>{# <input type="submit" value="submit" />#} <input type="button" value="AjaxSubmit" onclick="AjaxSubmit();"/></form><script src="{{ STATIC_URL }}js/jquery-2.1.4.min.js"></script><script type="text/javascript"> function AjaxSubmit(){ $.ajax({ url: '/login/', type: 'POST', data: {'username':'','password':''}, //就当提交了一个空数据,制造错误 success: function(arg){ //arg是返回值,必须是字符串 var callback_dict = $.parseJSON(arg); $('#uname_error').text(callback_dict.username[0].message); $('#pwd_error').text(callback_dict.password[0].message);{# console.log(callback_dict.username[0].message)#} } }) }</script> |
app01/forms/account.py
1 2 3 4 5 | from django import formsclass LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput()) |
browser


浙公网安备 33010602011771号