在项目中导入Flask-WTF
from flask_wtf import FlaskForm在项目中导入Flaks-WTF的HTML标准字段
from wtforms import StringField,PasswordField,SubmitField在项目中导入Flask-WTF的验证函数
from wtforms.validators import DataRequired, EqualTo在使用Flask-WTF拓展的时候,需要使用CSRF Token 在html页面中加入
{{ html_form.csrf_token() }}app.py
from flask import Flask, render_template, request, flash from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import DataRequired, EqualTo app = Flask(__name__) app.secret_key = "dsauhfabf" class LoginForm(FlaskForm): username = StringField('用户名', validators=[DataRequired()]) password1 = PasswordField('密码', validators=[DataRequired()]) password2 = PasswordField('确认密码', validators=[DataRequired(), EqualTo('password1', "两次密码填入不一致")]) submit = SubmitField('提交') @app.route('/form', methods=['GET', 'POST']) def login(): login_form = LoginForm() if request.method == 'POST': username = request.form.get('username') password1 = request.form.get('password1') password2 = request.form.get('password2') if login_form.validate_on_submit(): return 'success' else: flash("false") return render_template('demo3.html', html_form=login_form) if __name__ == '__main__': app.run()demo3.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post"> <br> {{ html_form.csrf_token() }} {{ html_form.username.label }}{{ html_form.username }}<br> {{ html_form.password1.label }}{{ html_form.password1 }}<br> {{ html_form.password2.label }}{{ html_form.password2 }}<br> {{ html_form.submit }}<br> {% for message in get_flashed_messages() %} {{ message }} {% endfor %} </form> </body> </html> 亓官劼 认证博客专家 Python 全栈 数据结构与算法 大家好,我是亓官劼(qí guān jié),在博客中分享数据结构与算法、Python全栈开发、Java后端开发、前端、OJ题解及各类报错信息解决方案等经验。一起加油,用知识改变命运,未来可期。若有事项需联系博主,可通过微信:qiguanjie2015 进行联系,有空会回复。