我无法从表单中获取数据库条目以显示在输出页面上。我认为这是我的flask-sqlalchemy查询,但我从文档中得不到任何内容。没有错误消息或回溯。代码如下:
表格页面的路线:
@app.route('/thing', methods=['GET', 'POST'])
def thing():
form = TForm()
return render_template(
'thing.html',
form=form,
page_title = 'Add It',
form_submit_label = 'Add Entry')
表单操作的路线:
@app.route('/addthing', methods=['POST'])
def add_thing():
form = TForm(request.form)
filename = ''
if request.method == 'POST' and form.validate_on_submit():
cover = request.files['cover']
if cover and allowed_file(cover.filename):
filename = secure_filename(cover.filename)
cover = cover.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return cover
t = Thing(
title = request.form['title'],
genre = request.form['genre'],
summary = request.form['summary'],
cover = cover
)
db.session.add(t)
db.session.commit()
flash('New entry was successfully posted')
return redirect(url_for('thinglist'))
模板路线:
@app.route('/thinglist', methods=['GET'])
def thinglist():
thing_entries = Thing.query.all()
# below thing_entries works, but it was just a way to test
# thing_entries = [{'title': 'No where fast', 'genre': ['red', 'blue'], 'summary': 'I love trains'},
# {'title': 'No why', 'genre': ['yellow', 'blue'], 'summary': 'I love lamp'},
# {'title': 'where fast', 'genre': ['red', 'green'], 'summary': 'I love cats'}]
return render_template(
'thinglist.html',
thing_entries=thing_entries,
page_title = 'Thing List')
事物清单模板
{% extends "layout.html" %}
{% block content %}
{% for entry in thing_entries %}
<article>
<div>
<div>
<img src="{{ entry.cover }}" alt="Cover for {{ entry.title }}" />
</div>
<div>
<ul>
<li class="">{{ entry.title }}</li>
<li class=""><strong>Genre: </strong>{{ entry.genre }}</li>
<li class=""><strong>Summary: </strong>{{ entry.summary|truncate( 30, true ) }}</li>
</ul>
</div>
</div>
</article>
{% else %}
<div class="no-entries">Nothing</div>
{% endfor %}
{% endblock %}
我尝试了Thing.query.all()行的许多变体,例如
Thing.query.filter_by(id=thing_id).all() ==> doesn't work
Thing.query.filter(thing_id) ==> doesn't work
Thing.query.get(thing_id) ==> doesn't work
我只是不明白。谢谢你的帮助。