WTForms是一个支持多个web框架的form组件,主要用于对用户请求数据进行验证
from flask import Blueprint from flask import request from flask import render_template from wtforms.fields import simple, core #simple:简单的字段 from wtforms import Form, validators #validators:校验条件 reg = Blueprint("reg", __name__) class RegForm(Form): username = simple.StringField( label="用户名:", #前端显示的字段
#default:None, #组件生成后的默认值 id="username", render_kw={"class": " form-control col-sm-2 "}, #为标签创建属性 validators=[ #声明校验条件 validators.DataRequired(message="用户名不能为空"), validators.Length(min=2, max=7, message="用户名不能小于%(min)d,不能大于%(max)d") ] ) password = simple.PasswordField( label="密码:", id="password",
render_kw={"class": " form-control col-sm-2 "}, validators=[ validators.DataRequired(message="密码不能为空"), validators.Length(min=6, max=16, message="用户名不能小于%(min)d,不能大于%(max)d") ] ) repassword = simple.PasswordField( label="确认密码", render_kw={"class": " form-control col-sm-2 "}, validators=[ validators.EqualTo("password", message="密码不一致") ] ) email = simple.StringField( label="邮箱", render_kw={"class": " form-control col-sm-2 "}, validators=[ validators.Email(message="邮箱格式不符") ] ) gender = core.RadioField( label="性别", choices=[ (1, "男"), (2, "女") ], coerce=int ) hobby = core.SelectMultipleField( label="爱好", choices=[ (1, "抽烟"), (2, "喝酒"), (3, "烫头"), ], coerce=int ) sub = simple.SubmitField( label="注册", ) @reg.route("/reg", methods=["GET", "POST"]) def reg_func(): if request.method == "GET": reg = RegForm() #实例化对象 return render_template("reg.html", reg=reg) else: new_reg = RegForm(formdata=request.form) if new_reg.validate(): return "注册成功" else: return render_template("reg.html", reg=new_reg)
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post" novalidate> {{ lf.username.label }} {{ lf.username }} {{ lf.username.errors.0 }} {{ lf.password.label }} {{ lf.password }} {{ lf.password.errors.0 }} {{ lf.sub }} </form> </body> </html>
reg.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> {% for f in regf %} {% if f.label == "登陆" %} <p>{{ f }}{{ f.errors.0 }}</p> {% else %} <p>{{ f.label }}{{ f }}{{ f.errors.0 }}</p> {% endif %} {% endfor %} </form> </body> </html>