Flask_WTF实现表单
阅读原文时间:2023年07月09日阅读:1

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.username.label }}{{ form.username }}
{{ form.password.label }}{{ form.password }}
{{ form.password2.label }}{{ form.password2 }}
{{ form.submit }}

完整代码:

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


Title

{{ form.username.label }}{{ form.username }}
{{ form.password.label }}{{ form.password }}
{{ form.password2.label }}{{ form.password2 }}
{{ form.submit }}

运行结果:

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章