form组件
1,对用户信息验证
-Ajax
-Form
2.生成HTML代码
3.创建一个类
类中创建字段(含正则表达式)
GET
obj=FiForm()
obj.user=>自动生成HTML
POST
obj=FIForm(request.POST)
if obj.is_valid():
obj.cleaned_data
else:
obj.errors
from django.shortcuts import render from django.shortcuts import redirect from django import forms from django.forms import fields #创建form类 当请求到来时,先匹配,匹配出正确和错误信息。 class FlForm(forms.Form): user=fields.CharField( max_length=23, min_length=8, required=True, error_messages={ 'max_length':'长了', 'min_length':'短了', 'required':'格式错误' } ) pwd=fields.CharField( min_length=12, required=True, error_messages={ 'min_length': '短了', 'required': '格式错误' } ) age=fields.CharField( required=True, error_messages={ 'required': '格式错误', 'invalid':'必须为数字' } ) email=fields.CharField( required=True, min_length=6, error_messages={ 'required':'邮箱不能为空', 'min_length': '短了', 'invalid': '邮箱格式错误' } ) def f1(request): if request.method=='GET': obj=FlForm() return render(request,'f1.html',{'obj':obj}) else: # u=request.POST.get('user') # p=request.POST.get('pwd') # e=request.POST.get('email') # a = request.POST.get('age') obj=FlForm(request.POST) v=obj.is_valid()#验证是否匹配成功 if v: print('验证成功',obj.cleaned_data) return redirect('http://www.xiaohuar.com') else: print('验证失败',obj.errors) return render(request, 'f1.html',{'obj':obj})
HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id="fm" action="/f1.html" method="POST"> <p>{{obj.user}}{{ obj.errors.user.0 }}</p> <p>{{obj.pwd}} {{ obj.errors.pwd.0 }}</p> <p>{{obj.email}}{{ obj.errors.email.0}}</p> <p>{{obj.age}}{{ obj.errors.age.0}}</p> <p><input type="submit" value="提交"/></p> <p><input type="button" value="Ajax提交" οnclick="submitAjaxFrom()"/></p> </form> <script src="jquery-3.1.1.min.js"></script> <script> function submitAjaxFrom() { $.ajax({ url:'/f1.html', type:'POST', data:$('#fm').serializeArray(), success:function (arg) { console.log(arg); } }) } </script> </body> </html>