```python # 定义表单类 from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired
class NameForm(FlaskForm): # 含有文本字段name和提交按钮submit name = StringField('What is your name?', validators=[DataRequired()]) submit = SubmitField('Submit')
{% extends "base.html" %} {% import "bootstrap/wtf.html" as wtf %} --导入模板元素 {% block title %}Flasky{% endblock %} {% block page_content %} <divclass="page-header"> <h1>Hello,{% if name %}{{ name }}{% else %}Stranger{% endif %}</h1> </div> {{ wtf.quick_form(form) }}--参数form为Flask-WTF表单对象,使用Bootstrap的默认样式渲染传入的表单 {% endblock %}
4.4 在视图函数中处理表单
完整代码
app.py
from flask import Flask, render_template from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired from flask_bootstrap import Bootstrap
# 定义表单类 classNameForm(FlaskForm):# 含有文本字段name和提交按钮submit name = StringField('What is your name?', validators=[DataRequired()]) submit = SubmitField('Submit')
@app.route('/', methods=['GET', 'POST']) defindex(): name = None form = NameForm() if form.validate_on_submit(): name = form.name.data form.name.data = '' return render_template('index.html', form=form, name=name)
{% extends "base.html" %} {% import "bootstrap/wtf.html" as wtf %} {% block title %}Flasky{% endblock %} {% block page_content %} <divclass="page-header"> <h1>Hello,{% if name %}{{ name }}{% else %}Stranger{% endif %}</h1> </div> {{ wtf.quick_form(form) }} {% endblock %}
4.5 重定向和用户会话
修改app.py
from flask import Flask, render_template,session,redirect,url_for from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired from flask_bootstrap import Bootstrap
# 定义表单类 classNameForm(FlaskForm):# 含有文本字段name和提交按钮submit name = StringField('What is your name?', validators=[DataRequired()]) submit = SubmitField('Submit')
@app.route('/', methods=['GET', 'POST']) defindex(): form = NameForm() if form.validate_on_submit(): session['name']=form.name.data return redirect(url_for('index')) return render_template('index.html', form=form, name=session.get('name'))
4.6 闪现消息
app.py
from flask import Flask, render_template,session,redirect,url_for,flash from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired from flask_bootstrap import Bootstrap
# 定义表单类 classNameForm(FlaskForm):# 含有文本字段name和提交按钮submit name = StringField('What is your name?', validators=[DataRequired()]) submit = SubmitField('Submit')
@app.route('/', methods=['GET', 'POST']) defindex(): form = NameForm() if form.validate_on_submit(): old_name=session.get('name') if old_name isnotNoneand old_name!=form.name.data: flash('looks like you have changed your name!') session['name']=form.name.data return redirect(url_for('index')) return render_template('index.html',form=form,name=session.get('name'))