一、介绍
用于生成HTML字段且验证字段的内容输入
二、下载
pip install wtforms
三、使用
1.定义form类
2.form类定义好字段、字段类型、验证规则
3.实例化form类
4.获取表单数据进行校验
'''
路由和视图
'''
from flask import Blueprint
from flask import render_template
from wtformsDemo.mywtforms import MyForm
from flask import request
formBlue = Blueprint("formBlue",__name__)
@formBlue.route("/reg",methods=["GET","POST"])
def reg():
form=MyForm(request.form) # 实例化自定义的wtforms
if request.method == "POST":
if form.validate(): # 对提交的数据进行验证
return "注册成功"
return render_template("reg.html",form=form)
'''
formDemo 自定义的form类
'''
from wtforms import Form,validators,widgets
from wtforms.fields import simple,core,html5
'''
simple 基础字段
core 核心字段
html5 h5新增的字段
'''
class MyForm(Form):
username = simple.StringField(
label="用户名", # 标签名称
render_kw={"placeholder":"请输入用户名"}, # 给input框添加属性
default="用户名", # 设置默认值
validators = [ # 设置验证条件
validators.Length(min=6,max=18,message="用户名长度必须大于%(min)d且小于%(max)d"), # 验证长度
validators.DataRequired(message="用户名不能为空"), # 验证不能为空
validators.Regexp(r'^[a-zA-Z]w{2,17}',message="必须字母开头"), # 正则表达式验证
]
)
password = simple.PasswordField(
label="密码",
validators= [
validators.Length(min=6, max=18, message="密码长度必须大于%(min)d且小于%(max)d"), # 验证长度
validators.DataRequired(message="密码不能为空"), # 验证不能为空
]
)
password2 = simple.PasswordField(
label="密码",
validators=[
validators.Length(min=6, max=18, message="密码长度必须大于%(min)d且小于%(max)d"), # 验证长度
validators.DataRequired(message="密码不能为空"), # 验证不能为空
validators.EqualTo("password",message="两次密码必须一致") # 检验两个字段是否相同
]
)
email = html5.EmailField(
label="邮箱",
validators=[
validators.DataRequired(message="邮箱不能为空"), # 邮箱不能为空验证
validators.Email(message="邮箱格式错误"), # 验证邮箱格式
],
)
gender = core.RadioField(
label="性别",
choices=((1,"男"),(2,"女")), # 设置choice选项
coerce=int # 接收到的数据转化为整型
)
city = core.SelectField(
label="城市",
choices=(
("bj","北京"),
("sh","上海"),
("sz","深圳"),
("gz","广州"),
("hz","杭州")
)
)
hobby = core.SelectMultipleField(
label="爱好",
choices=(
(1,"篮球"),
(2,"足球"),
),
coerce=int,
widget=widgets.ListWidget(prefix_label=False), # 改为列表的形式
option_widget=widgets.CheckboxInput(), # 更改渲染格式
)
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.hobby.choices = ( # 从数据库中获取数据,实现实时更新
(1,"篮球"),
(2,"足球"),
(3,"排球"),
)
# HTML
<body>
<form action="" method="post">
{% for field in form %}
<!--field.errors[0] 错误信息-->
<p>{{field.label}} :{{field}} {{field.errors[0]}}</p>
{% endfor %}
<input type="submit">
</form>
</body>