Flask-WTF表单的使用
Posted cerofang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask-WTF表单的使用相关的知识,希望对你有一定的参考价值。
使用flask的WTF表单
1 #! /usr/bin/env python 2 # *-* coding: utf-8 *-* 3 4 from flask import Flask, render_template, request, flash, make_response 5 from flask_wtf import FlaskForm 6 from wtforms.fields import * 7 from wtforms.validators import DataRequired, EqualTo 8 9 app = Flask(__name__) 10 # 开启session 11 app.secret_key = "aasdfsdf" 12 # app.config["SECRET_KEY"] = "abcd" 13 app.config["WTF_CSRF_ENABLED"] = False 14 15 16 @app.route(‘/‘) 17 def hello_world(): 18 return ‘Hello World!‘ 19 20 21 class Login(FlaskForm): 22 username = StringField(label="用户名", validators=[DataRequired("请输入用户名")]) 23 password = PasswordField(label="密码", validators=[DataRequired("请输入密码")]) 24 password2 = PasswordField(label="密码", validators=[DataRequired("请输入密码"), EqualTo(‘password‘, "密码输入不一致")]) 25 submit = SubmitField(label="提交") 26 27 28 @app.route("/login", methods=["GET", "POST"]) 29 def login(): 30 login_form = Login() 31 if request.method == ‘POST‘: 32 if login_form.validate_on_submit(): 33 username = request.form.get("username") 34 password = request.form.get("password") 35 password2 = request.form.get("password2") 36 print(username, password, password2) 37 # return make_response("success") 38 return "success" 39 else: 40 print("error") 41 flash("参数错误请重新输入") 42 # return render_template("demo004.html", form=login_form) 43 44 # else: 45 # print("get") 46 # return render_template("demo004.html", form=login_form) 47 return render_template("demo004.html", form=login_form) 48 49 50 # 定义根路由视图函数,生成表单对象,获取表单数据,进行表单数据验证 51 @app.route(‘/demo2‘, methods=["get", "post"]) 52 def demo2(): 53 register_form = Login() 54 # 验证表单 55 if register_form.validate_on_submit(): 56 # 如果代码能走到这个地方,那么就代码表单中所有的数据都能验证成功 57 username = request.form.get("username") 58 password = request.form.get("password") 59 password2 = request.form.get("password2") 60 # 假装做注册操作 61 print(username, password, password2) 62 return "success" 63 else: 64 if request.method == "POST": 65 flash("参数有误或者不完整") 66 67 return render_template(‘demo004.html‘, form=register_form) 68 69 70 if __name__ == ‘__main__‘: 71 app.run(debug=True)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <form method="post"> 9 {{ form.username.label }}{{ form.username }}<br/> 10 {{ form.password.label }}{{ form.password }}<br/> 11 {{ form.password2.label }}{{ form.password2 }}<br/> 12 {{ form.submit }} 13 </form> 14 15 {% for message in get_flashed_messages() %} 16 {{ message }} 17 {% endfor %} 18 19 </body> 20 </html>
以上是关于Flask-WTF表单的使用的主要内容,如果未能解决你的问题,请参考以下文章