数据显示&表单添加

数据显示

  • 定义路由函数,并将 Author 和 Book 的所有结果传到模板
@app.route('/',methods=['GET','POST'])
def index():
    author = Author.query.all()
    book = Book.query.all()
    return render_template('index.html',author=author,book=book)
  • 模版关键代码
<ul>
    {% for x in author %}
    <li>{{ x }}</li>
    {% endfor %}
</ul>
<hr>
<ul>
    {% for x in book %}
    <li>{{ x }}</li>
    {% endfor %}
</ul>
  • 效果图

表单添加

  • 定义表单类
from flask_wtf import FlaskForm
from wtforms.validators import DataRequired
from wtforms import StringField,SubmitField
#创建表单类,用来添加信息
class Append(FlaskForm):
    au_info = StringField(validators=[DataRequired()])
    bk_info = StringField(validators=[DataRequired()])
    submit = SubmitField(u'添加')
  • 传入至模版中
#创建表单对象
@app.route('/',methods=['GET','POST'])
def index():
    author = Author.query.all()
    book = Book.query.all()
    form = Append()
    return render_template('index.html',author=author,book=book,form=form)
  • 模板中代码
<form method="post">
    {{ form.csrf_token }}
    <p>作者:{{ form.au_info }}</p>
    <p>书名:{{ form.bk_info }}</p>
    <p>{{ form.submit }}</p>
</form>
  • 效果图