首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Django在template - dict键中显示字典列表是一个“变量”。

Django在template - dict键中显示字典列表是一个“变量”。
EN

Stack Overflow用户
提问于 2022-06-17 10:58:46
回答 1查看 574关注 0票数 0

我正在使用Django 4.0显示一个前端页面,其中源数据是dict列表。我想要排序的键,然后显示在列表中的所有迪克按相同的顺序。这是我的views.py:

代码语言:javascript
运行
复制
def UserGoalstatus(request, promise_token):
    print("__UserGoalstatus__")
    from cmd_utils import Retrieve_goal
    data = Retrieve_goal(promise_token)
    keys = set()
    for item in data:
        keys.update(set(item))  
    key_order = sorted(keys)  

context = {
    "data": data,
    "key_order": key_order,
}
return render(request, 'json_table.html', context)

以下是我的“数据”变量的内容:

代码语言:javascript
运行
复制
[
{'goal_key': '286815', 'goal_type': 'hotelreservation', 'goal_id': 16149845, 'promise_token': '9ba51cbc-830b-64d603904099', 'campaign_id': 1002204, 'properties': {'price': 100, 'created': '2022-06-13 10:48:34', 'checkout': '2022-06-13', 'currency_code': 'USD', 'completed_booking_status': 1}}, 
{'goal_key': '1208107', 'goal_type': 'hotelreservation', 'goal_id': 16149846, 'promise_token': '9ba51cbc-830b-64d603904099', 'campaign_id': 1002204, 'properties': {'price': 100, 'created': '2022-06-13 10:48:35', 'checkout': '2022-06-13', 'currency_code': 'USD', 'completed_booking_status': 1}}
]

这是我的html文件,我想按'key_order‘顺序打印数据中的所有内容。

代码语言:javascript
运行
复制
<table id="dtBasicExample" class="table table-hover table-striped table-bordered" cellspacing="0" width="100%">
    <thead>
        <tr>
            {% for key in key_order %}
            <th>{{ key }}</th>
            {% endfor %}
        </tr>
    </thead>
    <tbody>
        {% for item in data %}
        <tr>
            {% for key in key_order %}
            <td>{{ item.get(key) }}</td>
            {% endfor %}
        </tr>
        {% endfor %}
    </tbody>
</table>

这部分似乎不对:{{ item.get(键) }},有人可以建议正确的方法来访问到特定的值映射吗?

EN

Stack Overflow用户

回答已采纳

发布于 2022-06-20 06:45:44

这是我的解决办法

我需要定义我自己的django模板过滤器

关键部分是'get_item‘,它现在可以将字典键解析为Django html中的'variable’。有关更详细的信息,请参阅以下链接:

Django指南

stackoverflow回答

views.py

代码语言:javascript
运行
复制
# customized template for html
from django.template.defaulttags import register

@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

在json_table.html中

代码语言:javascript
运行
复制
<table id="dtBasicExample" class="table table-hover table-striped table-bordered" cellspacing="0" width="100%">
    <thead>
        <tr>
            {% for key in key_order %}
            <th>{{ key }}</th>
            {% endfor %}
        </tr>
    </thead>
    <tbody>
        {% for item in data %}
        <tr>
            {% for key in key_order %}
            <td>{{ item | get_item:key}}</td>
            {% endfor %}
        </tr>
        {% endfor %}
    </tbody>
</table>
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72658343

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档