You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CS50X Lab9:Flask+Jinja无法渲染数据库表格至网页求助

解决Flask查询数据无法传递到Jinja模板的问题

你的问题根源很明确:Flask后端查询到数据库数据后,没有将数据传递给前端模板,导致Jinja无法读取tableau变量进行渲染。

修正步骤

在Flask的GET请求处理分支中,调用render_template时需要把查询到的tableau变量传递给模板:

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        bname = request.form.get("name")
        bday = request.form.get("day")
        bmonth = request.form.get("month")

        db.execute("INSERT INTO birthdays (name, month, day) VALUES (?, ?, ?)", bname, bmonth, bday)

        return redirect("/")

    else:
        tableau = db.execute("SELECT * FROM birthdays")
        # 关键:将tableau变量传递给模板
        return render_template("index.html", tableau=tableau)

额外优化建议

你的HTML表格中"Birthday"列只显示了月份,建议改成月份+日期的组合,更符合需求:

<div class="section">
    <h2>All Birthdays</h2>
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Birthday</th>
            </tr>
        </thead>
        <tbody>
            {% for row in tableau %}
            <tr>
                <td>{{ row['name'] }}</td>
                <td>{{ row['month'] }}/{{ row['day'] }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>

内容的提问来源于stack exchange,提问作者TheAstroNot08

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 20:42:00