思南1900

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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:

from django.shortcuts import render
from django.shortcuts import redirect
from django.shortcuts import HttpResponse


from django import forms
from django.forms import fields
class F1Form(forms.Form):
user = fields.CharField(
max_length=18,
min_length=6,
required=True,
error_messages={'required': '用户名不能为空','max_length': '太长了','min_length': '太短了','invalid':'..'}
)
pwd = fields.CharField(required=True,min_length=32)
age = fields.IntegerField(
required=True
)
email = fields.EmailField(
required=True,
min_length=8
)


def f1(request):
if request.method == 'GET':
obj = F1Form()
return render(request,'f1.html',{'obj':obj})
else:
obj = F1Form(request.POST)
# 是否全部验证成功
if obj.is_valid():
# 用户提交的数据
print('验证成功',obj.cleaned_data)
return redirect('http://www.xiaohuar.com')
else:
print('验证失败',obj.errors)
return render(request, 'f1.html',{'obj':obj})

templates:
<!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.age }}{{ obj.errors.age.0 }}</p>
<p>{{ obj.email }}{{ obj.errors.email.0 }}</p>
<input type="submit" value="提交" />
</form>
<script src="/static/jquery-3.1.1.js"></script>

</body>
</html>
posted on 2018-02-18 15:18  思南1900  阅读(120)  评论(0编辑  收藏  举报