#使用 WTForms 进行表单验证的例子 from wtforms import Form from wtforms import BooleanField from wtforms import TextField from wtforms import PasswordField from wtforms import validators #注册表单 class RegisterForm(Form): username = TextField("Username",[validators.length(min=4, max=25)]) email = TextField("Email Address", [validators.length(min=6, max=25)]) password = PasswordField("New Password", [validators.Required(), validators.EqualTo("confirm", message="Passwords must match")]) confirm = PasswordField("Repeat Password") accept_tos = BooleanField("I accept the TOS", [validators.Required()]) #视图函数 @app.route("/register", methods=["GET", "POST"]) def register(): form = RegisterForm(request.form) if request.method == "POST" and form.validate(): user = User(form.username.data, form.email.data, form.password.data) db_session.add(user) flash("Thanks for registering") return redirect(url_for("login")) return rendertemplate("regiser.html", form=form) #备忘表 # 1、如果数据是以POST方式提交的,那么基于请求的form属性的值创建表单,反过来,如果是以get提交的,就从args属性创建 # 2、验证表单数据,调用validate()方法,如果数据验证通过,此方法将会返回True,否则返回False # 3、访问表单的单个值,使用form.<NAME>.data #模版中的表单 {% macro render_field(field) %} <dt>{{ field.label }} <dd>{{ field(**kwargs)|safe }} {% if field.errors %} <ul class=errors> {% for error in field.errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %} </dd> {% endmacro %}