Django内置Form组件
- 对用户请求的验证
- AJax
- Form
- 生成HTML代码
a. 创建一个类
b. 类中创建字段(包含正则表达式)
c. GET
obj = Fr()
obj.user = > 自动生成HTML
d. POST
obj = Fr(request.POST)
if obj.is_valid():
obj.cleaned_data
else:
obj.errors
return .... obj
直接上代码:
views.py
1 from django.shortcuts import render
2 from django.shortcuts import redirect
3 from django.shortcuts import HttpResponse
4
5
6 from django import forms
7 from django.forms import fields
8 class F1Form(forms.Form):
9 user = fields.CharField(
10 max_length=18,
11 min_length=6,
12 required=True,
13 error_messages={
'required': '用户名不能为空','max_length': '太长了','min_length': '太短了','invalid':'..'}
14 )
15 pwd = fields.CharField(required=True,min_length=32)
16 age = fields.IntegerField(
17 required=True
18 )
19 email = fields.EmailField(
20 required=True,
21 min_length=8
22 )
23
24
25 def f1(request):
26 if request.method == 'GET':
27 obj = F1Form()
28 #自动生成HTML代码
29 return render(request,'f1.html',{
'obj':obj})
30 else:
31 obj = F1Form(request.POST)
32 # 是否全部验证成功
33 if obj.is_valid():
34 # 用户提交的数据
35 print('验证成功',obj.cleaned_data)
36 return redirect('http://www.baidu.com')
37 else:
38 print('验证失败',obj.errors)
39 return render(request, 'f1.html',{
'obj':obj})
f1.html
1 DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Titletitle>
6 head>
7 <body>
8 <form id="fm" action="/f1.html" method="POST">
9 <p>{
{ obj.user }}{
{ obj.errors.user.0 }}p>
10 <p>{
{ obj.pwd }}{
{ obj.errors.pwd.0 }}p>
11 <p>{
{ obj.age }}{
{ obj.errors.age.0 }}p>
12 <p>{
{ obj.email }}{
{ obj.errors.email.0 }}p>
13 <input type="submit" value="提交" />
14 form>
15 <script src="/static/jquery-3.1.1.js">script>
16
17 body>
18 html>