
一、Form提交验证与Ajax提交验证的运用实例
Form表单提交时会刷新页面,输入失败时,输入框内内容也会随之刷新不能保留;而Ajax提交是在后台偷偷提交,不会刷新页面,因此也就可以保留页面输入框内的内容。
1. 浏览器访问
http://127.0.0.1:8000/login/ http://127.0.0.1:8000/register/
2. urls
from django.conf.urls import url
from django.contrib import admin
from app01 import views urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/', views.login),
url(r'^ajax_login/', views.ajax_login),
url(r'^test/', views.test),
url(r'^register/', views.register),
]
3. views
from django.shortcuts import render,redirect,HttpResponse
from django.forms import Form
from django.forms import fields
from django.forms import widgets
导入模块
class LoginForm(Form):
user = fields.CharField(required=True)
pwd = fields.CharField(min_length=18) def login(request):
"""
obj = xxx(request.POST)
# 是否校验成功
v = obj.is_valid()
# html标签name属性 = Form类字段名 # 所有错误信息
obj.errors # 正确信息
obj.cleaned_data
"""
if request.method == 'GET':
return render(request,'login.html')
else:
obj = LoginForm(request.POST)
"""
1.LoginForm实例化时,
self.fields={
'user':正则表达式
'pwd':正则表达式
}
2.循环self.fields
flag = True
errors
cleaned_data
for k,v in self.field.items():
#1.user,正则表达式
input_value = request.POST.get(k)
正则表达式和input_value
flag = False
:return flag
"""
if obj.is_valid():
print(obj.cleaned_data) #拿到正确信息
return redirect('http://www.baidu.com')
return render(request,'login.html',{'obj': obj}) #拿到错误信息返回login.html(带着错误信息一起) def ajax_login(request):
import json
ret = {'status': True,'msg': None}
obj = LoginForm(request.POST)
if obj.is_valid():
print(obj.cleaned_data)
else:
# print(obj.errors) # obj.errors对象 #拿到错误信息
ret['status'] = False
ret['msg'] = obj.errors
v = json.dumps(ret)
return HttpResponse(v) class TestForm(Form):
t1 = fields.CharField(required=True,max_length=8,min_length=2,
error_messages={
'required': '不能为空',
'max_length': '太长',
'min_length': '太短',
}
)
t2 = fields.EmailField() def test(request):
if request.method == "GET":
obj = TestForm()
return render(request,'test.html',{'obj': obj})
else:
obj = TestForm(request.POST)
if obj.is_valid():
print(obj.cleaned_data)
else:
print(obj.errors)
return render(request,'test.html',{'obj':obj}) class RegiterForm(Form):
user = fields.CharField(min_length=8)
email = fields.EmailField()
password = fields.CharField()
phone = fields.RegexField('139\d+') def register(request):
if request.method == 'GET':
obj = RegiterForm()
return render(request,'register.html',{'obj':obj})
else:
obj = RegiterForm(request.POST)
if obj.is_valid():
print(obj.cleaned_data)
else:
print(obj.errors)
return render(request,'register.html',{'obj':obj})
views
4. templates
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>用户登录</h1>
<form id="f1" action="/login/" method="POST">
{% csrf_token %}
<p>
<input type="text" name="user" />{{ obj.errors.user.0 }}
</p>
<p>
<input type="password" name="pwd" />{{ obj.errors.pwd.0 }}
</p>
<input type="submit" value="提交" />
<a onclick="submitForm();">提交</a>
</form>
<script src="/static/jquery-3.2.1.js"></script>
{# ajax提交时在后台偷偷提交,不会刷新页面,这也就保留了输入框内的数据#}
<script>
function submitForm(){
$('.c1').remove();
$.ajax({
url: '/ajax_login/',
type: 'POST',
data: $('#f1').serialize(),// user=alex&pwd=456&csrftoen=dfdf\
dataType:"JSON",
success:function(arg){
console.log(arg);
if(arg.status){ }else{
$.each(arg.msg,function(index,value){
console.log(index,value);
var tag = document.createElement('span');
tag.innerHTML = value[0];
tag.className = 'c1';
$('#f1').find('input[name="'+ index +'"]').after(tag);
})
}
}
})
}
</script>
</body>
</html>
login
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body> <form action="/register/" method="POST" novalidate> {# novalidate 提交表单时让浏览器不对其进行验证 #}
{% csrf_token %}
<p>
{{ obj.user }} {{ obj.errors.user.0 }}
</p>
<p>
{{ obj.email }} {{ obj.errors.email.0 }}
</p>
<p>
{{ obj.password }} {{ obj.errors.password.0 }}
</p>
<p>
{{ obj.phone }} {{ obj.errors.phone.0 }}
</p>
<input type="submit" value="提交" />
</form>
</body>
</html>
register
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="/test/" method="POST" novalidate>
{% csrf_token %}
<p>
{{ obj.t1 }}{{ obj.errors.t1.0 }}
</p>
<p>
{{ obj.t2 }}{{ obj.errors.t2.0 }}
</p>
<input type="submit" value="提交" />
</form>
</body>
</html>
test
5. 运行显示截图