WTForms支持的HTML标准字段

WTForms常用验证函数

使用Flask-WTF需要配置参数SECRET_KEY。
CSRF_ENABLED是为了CSRF(跨站请求伪造)保护,SECRET_KEY用来生成加密令牌,当CSRF激活的时候,该设置会根据设置的密钥生成加密令牌
from flask import Flask,render_template
from flask_wtf import FlaskForm
from wtforms import StringField,PasswordField,SubmitField
from wtforms.validators import DataRequired,EqualTo
app = Flask(__name__)
app.config["SECRET_KEY"] = "asdfewq"
#定义表单的模型类
class RegisterForm(FlaskForm):
"""
自定义的注册表单模型类
"""
# label为字段说明标签,第二个参数验证器
# DataRequired 保证数据必须填写,并且不能为空
user_name = StringField(label="用户名",validators=[DataRequired("用户名不能为空")])
password = PasswordField(label="密码",validators=[DataRequired("密码不能为空")])
password2 = PasswordField(label="确认密码",validators=[DataRequired("确认密码不能为空"),
EqualTo("password","两次密码不一致")])
submit = SubmitField(label="提交")
@app.route("/register")
def register():
# 创建表单对象
form = RegisterForm()
return render_template("register.html",form=form)
if __name__ == '__main__':
app.run(debug=True)
register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post">
{{ form.user_name.label }}
<p>{{ form.user_name }}</p>
{% for msg in form.user_name.errors %}
<p>{{ msg }}</p>
{% endfor %}
{{ form.password.label }}
<p>{{ form.password }}</p>
{% for msg in form.password.errors %}
<p>{{ msg }}</p>
{% endfor %}
{{ form.password2.label }}
<p>{{ form.password2 }}</p>
{% for msg in form.password2.errors %}
<p>{{ msg }}</p>
{% endfor %}
{{ form.submit }}
</form>
</body>
</html>


网友评论