Flask-WTForms 简单使用

时间:2022-05-11 00:10:51

安装 wtforms 2.2.1

直接上代码:

app.py 文件:

from flask import Flask, render_template, request
from wtforms import Form, validators
from wtforms.fields import simple, core # form 字段设计
class RegForm(Form):
# simple 字段类型
# StringField 和 TextAreaField 都是字符串的意思,StringField支持的类型少于StringField
username = simple.StringField(
label="用户名",
validators=[ # validators -- 校验信息
validators.DataRequired(message="用户不能为空"), # DataRequired -- 当前的地方必须填写数据; message -- 错误信息
validators.length(min=4, max=8, message="用户名必须大于等于4小于等于8") # length -- 长度
],
render_kw={"class": "my_class"} # 添加 class
) password = simple.PasswordField(
label="密码",
validators=[
validators.DataRequired(message="密码不能为空"),
validators.length(min=6, max=16, message="密码必须大于等于6小于等于16")
],
render_kw={"class": "my_class"} # 添加 class
) repassword = simple.PasswordField(
label="重复密码",
validators=[
validators.DataRequired(message="重复密码不能为空"),
validators.EqualTo("password", message="两次密码不一致") # EqualTo("字段名称") 判断该字段是否等于"字段名称"中的值
]
) gender = core.SelectField( # 单选字段在核心模块(支持的类型多)中才有
label="性别",
choices=( # 选项
(1, "女"),
(2, "男")
),
default=2, # 默认值
coerce=int # 指定前端提交过来的选项的类型是数字还是字符串 下边有验证
) email = simple.StringField(
label="邮箱",
validators=[
validators.Email(message="不符合规定")
]
) hobby = core.SelectMultipleField( # 多选字段
label="爱好",
choices=(
("", "读书"),
("", "美食"),
("", "电影"),
("", "音乐"),
),
default=("", "", "", ""),
coerce=str # 指定前端提交过来的选项的类型是数字还是字符串 下边有验证
) app = Flask(__name__) # 实例化 app reg_form = RegForm() # form信息(对象)赋值给reg_form @app.route("/form_reg", methods=["GET", "POST"])
def reg():
if request.method == "GET":
return render_template("form_reg.html", reg_form=reg_form)
if request.method == "POST":
reg_form_data = RegForm(request.form) # 拿到前端传过来的数据(request.form),给RegForm进行校验
if reg_form_data.validate(): # 如果前段穿过来的数据通过校验
print(type(reg_form_data.data.get("gender"))) # <class 'int'>
print(reg_form_data.data.get("hobby")) # ['1', '2', '3', '4']
return " * {注册成功} * 愿世界和平,无病无灾"
else:
# 前端传过来的内容未通过校验,返回注册页面, 附带注册提交的错误数据和错误提示
return render_template("form_reg.html", reg_form=reg_form_data) if __name__ == '__main__':
app.run()

form_reg.html 文件:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-Type" charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title> <style>
.my_class{
width: 500px;
}
</style>
</head>
<body>
<h1>注册页面</h1>
<form action="" method="post" enctype="multipart/form-data" novalidate>
{% for field in reg_form %}
<p>{{ field.label }}: {{ field }} <span style="color: red">{{ field.errors.0 }}</span> </p>
{% endfor %} {# {{ reg_form.username.label }}: {{ reg_form.username }}{{ reg_form.username.errors.0 }}<br>#}
{# {{ reg_form.password.label }}: {{ reg_form.password }}{{ reg_form.password.errors[0] }}<br>#} <input type="submit" value="提交">
</form>
</body>
</html>