Flask_WTF实现表单
作者:互联网
Flask_WTF实现表单可分为六个步骤:
①导入FlaskForm扩展包(from flask_wtf import FlaskForm)
②导入StringField,PasswordField,SubmitField (from wtforms import StringField,PasswordField,SubmitField)
③定义表单类
class RegisterForm(FlaskForm): username = StringField('账号:') password = PasswordField('密码:') password2 = PasswordField('确认密码:') submit=SubmitField('提交')
④定义路由
@app.route('/regist',methods=['GET','POST']) def regist_form(): redist_form=RegisterForm() return render_template('registform.html',form=redist_form)
⑤html文件中实现表单
<form method="post"> {{ form.username.label }}{{ form.username }}<br> {{ form.password.label }}{{ form.password }}<br> {{ form.password2.label }}{{ form.password2 }}<br> {{ form.submit }} </form>
完整代码:
app.py
from flask import Flask,render_template,request,flash from flask_wtf import FlaskForm from wtforms import StringField, PasswordField,SubmitField app = Flask(__name__) app.secret_key='yingjie' # 定义表单类 class RegisterForm(FlaskForm): username = StringField('账号:') password = PasswordField('密码:') password2 = PasswordField('确认密码:') submit=SubmitField('提交') @app.route('/regist',methods=['GET','POST']) def regist_form(): redist_form=RegisterForm() return render_template('registform.html',form=redist_form) if __name__ == '__main__': app.run()
registform.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post"> {{ form.username.label }}{{ form.username }}<br> {{ form.password.label }}{{ form.password }}<br> {{ form.password2.label }}{{ form.password2 }}<br> {{ form.submit }} </form> </body> </html>
运行结果:
标签:__,password2,form,Flask,app,表单,WTF,label,PasswordField 来源: https://www.cnblogs.com/zyj3955/p/15368164.html