Web表单
1.安装flask-wtf模块
(venv) $ pip install flask-wtf
2.导入和定义表单类
使用 Flask-WTF 时,每个 Web 表单都由一个继承自 Form 的类表示。这个类定义表单中的
一组字段,每个字段都用对象表示。字段对象可附属一个或多个验证函数。验证函数用来
验证用户提交的输入值是否符合要求。
from flask_wtf import Form, FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import Required
import os
app.config['SECRET_KEY']=os.urandom(20)
class NameForm(FlaskForm):
"""docstring for NameForm"""
name = StringField('What is your name?', validators=[Required()])
submit = SubmitField('Submit')
@app.route('/',methods=['GET','POST'])
def index():
name = None
form = NameForm()
if form.validate_on_submit():
name = form.name.data
form.name.data = ''
#return '<h1>Hello World!!</h1>'
#return render_template('index.html',current_time=datetime.utcnow())
return render_template('index.html',form=form,name=name)
3.index.html
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %}Flasky{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>Hello,{% if name %}{{ name }}{% else %}Stranger{% endif %}!</h1>
</div>
{{ wtf.quick_form(form) }}
{% endblock %}
4.最终页面