Flask应用程序未按预期显示列表

时间:2018-01-04 03:27:49

标签: flask jinja2

我有一个应用程序,使用美丽的汤擦拭网站。它为我返回表格中的数据。我使用wtforms和sqlite3查询实现了一个搜索栏。

Web page sample

这会返回我想要的数据,但不会返回我想要的数据。一旦我提交搜索,它就会在页面上而不是在索引上加载列表。

the results after search

这是我的烧瓶应用程序(部分):

@app.route('/', methods=('GET', 'POST'))
def index():
    products = get_products()
    form = SearchForm()
    if form.validate_on_submit():
        item = '%' + form.searchFor.data + '%'
        c.execute("SELECT * FROM supplementInfo WHERE (name) LIKE (?)", (item,))
        search_results = c.fetchall()
        return str(search_results)

    return render_template('index.html', products=products, form=form)

这是html:

<div col-12 class="wrap">
        <div class="search">
            <form method="POST" action="/">
                {{ form.csrf_token }}
                {{ form.searchFor(class_="searchTerm") }}
                <button type="submit" class="searchButton">
                    <i class="icon-search"></i>
                </button>
            </form>
        </div>
    </div>

<div class="infoTable">
<table>
    {% for row in products %}
        <tr>
            <td>{{ row[0] }}</td>
            <td> {{ row[1] }}</td>
            <td> {{ row[2] }}</td>
            <td> {{ row[3] }}</td>
        </tr>
    {% endfor %}
</table>
</div>

</center>

<div>
    <table>
        {% for item in search%}
        <tr>
            <td>{{ item.name}}</td>
        </tr>
        {% endfor %}
    </table>

</div>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

好的,我明白了。我不得不将应用程序更改为:

@app.route('/', methods=('GET', 'POST'))
def index():
    products = get_products()
    form = SearchForm()
    if form.validate_on_submit():
        item = '%' + form.searchFor.data + '%'
        c.execute("SELECT * FROM supplementInfo WHERE (name) LIKE (?)", (item,))
        search_results = c.fetchall()
        return render_template('index.html', products=products, form=form, search_results=search_results)
    return render_template('index.html', products=products, form=form)

我意识到我正在返回列表而不是返回模板并将其传递给列表。