view.py 配置
1 from django import forms 2 from django.forms import fields 3 # Create your views here. 4 5 class f1form(forms.Form): 6 user = fields.CharField(max_length=10,min_length=5,required=True,error_messages={'required':'不能为空','max_length':'太长了'}) #required不能为空 7 pwd = fields.CharField(max_length=9,min_length=6,required=True) 8 age = fields.IntegerField(required=True,error_messages={'required':'不能为空','invalid':'年龄格式错误'}) #invalid所有格式错误可以用这个 9 email = fields.EmailField(required=True,min_length=6,error_messages={'required':'不能为空','invalid':'邮箱格式错误'}) 10 #user pwd age email 需要跟from表单里面的name 值一致 11 12 13 def f1(request): 14 if request.method == "GET": 15 return render(request,'f1.html') 16 elif request.method == "POST": 17 # u = request.POST.get('user') 18 # p = request.POST.get('pwd') 19 # e = request.POST.get('email') 20 # a = request.POST.get('age') 21 # print(u,p,e,a ) 22 23 f = f1form(request.POST) #拿到上面的class 然后把post 里面传递进去进行验证 24 v = f.is_valid() #表示验证中 25 if v: #全部验证成功 26 print("验证成功",f.cleaned_data) #打印用户提交的数据,是一个字典数据 27 return redirect('http://www.xunlei.tv') 28 else: 29 print("验证失败",f.errors) #打印用户所有的错误数据 30 return render(request,'f1.html',{'f':f})
html 配置
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id="fm" action="f1.html" method="POST"> {{ f.errors }} <input type="text" name="user">{{ f.errors.user.0}} </br> <input type="text" name="pwd">{{ f.errors.pwd.0 }} </br> <input type="text" name="email">{{ f.errors.email.0 }} </br> <input type="text" name="age">{{ f.errors.age.0 }} </br> <input type="submit"> <input type="button" value="ajax提交" onclick="aj()"> </form> <script src="/static/jquery-3.3.1.min.js"></script> <script> function aj() { $.ajax({ url:'/f1.html', type:'POST', data:$('#fm').serialize(), success:function(arg) { alert(arg); } }) } </script> </body> </html>