WTForms是一个支持多个web框架的form组件,主要用于对用户请求数据进行验证
from flask import Blueprint from flask import request from flask import render_template from wtforms.fields import simple, core from wtforms import Form, validators reg = Blueprint("reg", __name__) class RegForm(Form): username = simple.StringField( label="用户名:", 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)
原文:https://www.cnblogs.com/wanglan/p/10574198.html