【问题标题】:How to pass a list instead of dictionary in python-django to html page如何将python-django中的列表而不是字典传递给html页面
【发布时间】:2019-11-21 21:07:47
【问题描述】:

我想在我的 html 页面“home.html”中显示列表“response_body” 为此,我从 response_body 中检索了 id 属性,并将存储在“id”变量中的最后一个 id 打印到我的 html 文件中。

我想检索所有的 id 并将其打印到 html 页面 我知道这将通过循环来完成,但是如何?

我是 django 和 python 的新手,任何帮助将不胜感激。

我曾尝试在循环结束之前打印最后一个 id,并且我成功了,但现在我想打印循环中的所有 id。

我尝试将 response_body 传递给 html 而不是 context,但它给了我一个错误,因为 response_body 是一个列表类型,它要求我传递一个字典变量,如 context 工作正常。

如何打印 reponse_body 列表中的所有 id

home.html

<p>results</p>
<p>{{id}}</p>

views.py 因为这是一个相当长的代码,所以我只发布可能有用的代码。

response_body = json.loads(response.read().decode('utf-8'))

for j in response_body:
    print(j['id'])
    id = j['id']

context = {
    'id': id,
}

return render(request, 'home.html', context)

【问题讨论】:

    标签: python html django django-views


    【解决方案1】:

    它非常简单。只需将列表发送到字典中即可:

    context = {
        'ids': [j['id'] for j in response_body],
        'response' : response_body,
        'dict_values': {'a':1, 'b':2}  # a dummy dictonary
    }
    
    return render(request, 'home.html', context)
    

    并更新模板:

    <p>results</p>
    {% for id in ids %}
        <p>{{id}}</p>
    {% endfor %}
    
    <p> Response Body </p>
    {% for r in response %}
            {{ r.id }}
            {{ r.description }}
            // and so on
    {% endfor %}
    <p> dummy dict </p>
    {% for key, value in dict_values.items %}
        {{ key }} {{ value }}
    {% endfor %}
    

    【讨论】:

    • 对我有用,如果我想再将一本字典传递给同一个 home.html 文件,我该怎么做?
    • 字典中的另一个条目还是另一个字典?你能更新一下问题吗?
    • 其实两者都有。我实际上想这样做,但这不会打印描述context = { 'ids': [j['id'] for j in response_body], 'descriptions': [j['description'] for j in response_body], } return render(request, 'table.html', context)
    • 我还想传递另一本字典,其中包含其他内容,例如return render(request, 'table.html', context, context2) 有可能吗?如果是我如何在我的 html 文件中引用它
    • 您是否遍历了模板中的新列表,例如{% for d in descriptions %} &lt;p&gt;{{d}}&lt;/p&gt; {% endfor %}
    猜你喜欢
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    相关资源
    最近更新 更多