wtf的作用:
1. 在内部已经为我们封装好了前端页面的form
2. 已经做好了校验的工作
代码实现:
# coding:utf-8
from flask import Flask,render_template,request
from flask_wtf import FlaskForm
from wtforms import StringField,PasswordField,SubmitField
from wtforms.validators import DataRequired,EqualTo
app = Flask(__name__)
# 如果使用wtf框架,在内部已经使用了session
app.config["SECRET_KEY"] = 'ryang'
class RegisterForm(FlaskForm):
"""定义自己的注册类"""
# DataRequired :必须输入值
# validator: 校验
user_name = StringField(label = u"用户名",validators=[DataRequired(u'必须填写用户名')])
password = PasswordField(label=u'密码',validators=[DataRequired(u'必须填写密码')])
# EqualTo(""):第一参数表示想要跟谁校验 第二个参数是提示信息
password2 = PasswordField(label=u'确认密码',validators=[DataRequired(u'必须填写密码'),
EqualTo('password',u'两次输入不一致')])
submit = SubmitField(u'注册')
@app.route("/register",methods=["GET","POST"])
def register():
if request.method == "GET":
form = RegisterForm()
return render_template('05_wtf.html',form = form)
else:
form = RegisterForm()
# validate_on_submit:作用是在提交的时候进行检验
# true表示校验通过 false表示校验失败
if form.validate_on_submit():
name = form.user_name.data
pwd = form.password.data
print("name = %s" %name)
print("pwd = %s" %pwd)
return "注册成功"
else:
return render_template("05_wtf.html",form = form)
if __name__ == '__main__':
app.run(debug=True)
前端页面的实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
{{ form.csrf_token }}
<!--获取到文本的标签-->
{{ form.user_name.label }}
<!--表示文本输入框-->
{{ form.user_name }} <br>
<!-- 获取form表单中的所有的错误信息-->
{% for msg in form.user_name.errors %}
{{ msg }} <br>
{% endfor %}
{{ form.password.label }}
{{ form.password }} <br>
{% for msg in form.password.errors %}
{{ msg }} <br>
{% endfor %}
{{ form.password2.label }}
{{ form.password2 }} <br>
{% for msg in form.password2.errors %}
{{ msg }} <br>
{% endfor %}
{{ form.submit }}
</form>
</body>
</html>