【问题标题】:Flask correct variable value on terminal but not in HTML template在终端上烧瓶正确的变量值,但在 HTML 模板中没有
【发布时间】:2019-02-24 19:06:04
【问题描述】:

Similar question 这并不能解决我的问题。

我有一个 Flask 应用程序,它从数据库中读取数据并使用数据库数据呈现 HTML 模板。在将它发送到 HTML 模板之前,我试图操纵从数据库获得的值,但这不起作用。

Python 代码:

@app.route('/pilot', methods=['GET'])
def form_view():
    result = {}
    # query DB and get cursor

    numQuestions = 0
    for row in cursor:
        row.pop('_id', None)        # delete the key and add modified key back
        row['_id'] = row['stage'][-1] # get only last char- eg, "1" from "stage1", "2" from "stage2" and so on
        print(row['_id'])
        result[numQuestions] = row
        numQuestions += 1

    return render_template("form.html", count=numQuestions, result=result, debug=app.debug)

在终端上运行时的输出符合预期:

1
1
1
2
2
2

form.html 的 Jinja2 片段:

{% for row in result[row_num]['scrutiny_stage'] %}
    {{ row['_id'] }}
{% endfor %}

浏览器输出:

stage1 stage1 stage1 stage2 stage2 stage2 stage2 

谁能帮我理解我在这里做错了什么以及如何获得我在 Python 代码中设置的变量的正确值以显示在 Flask 呈现的 HTML 模板中?

谢谢。

【问题讨论】:

  • 此代码无法给出该结果。您传递给模板的 result 对象没有 scrutiny_stage 嵌套字典。该模板中的row_num 是什么?如果您希望我们诊断发生了什么,您需要显示真实代码。
  • 你打印 (row['_id']) 并在结果字典中添加行,当然有区别。

标签: python flask


【解决方案1】:

感谢大家的提示,尽管我无法分享所有上下文(因为我必须保护专有信息),但他们很有帮助。我设法通过多个步骤解决了这个问题:

  1. 我重新构建了我的数据库架构,以便每个文档都有一个带有纯数字值的“_id”键。我删除了 'stage': 'stage1' 种字段。 “阶段”现在在代码库中根据数据库查询结果动态计算。
  2. 然后我更改了 Flask 视图函数,将“stage”键添加到传递给 HTML 模板的结果字典中(不要乱用“_id”字段):
numQuestions = 0

for row in cursor:
    for line in row['scrutiny_stage']:
        row['stage'] = line['_id']

    result[numQuestions] = row
    numQuestions += 1
  1. 最后,在我的 Jinja2 块中,我意识到我需要将结果作为 dict 进行操作,因此我将其更改为使用 dict.values() 方法:
    {% for row in result.values() %}
        {{ row['stage'] }}
    {% endfor %}

现在,我在终端和浏览器中打印了相同的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 2018-12-03
    • 1970-01-01
    相关资源
    最近更新 更多