繁体   English   中英

无法访问Django模板中的python字典键

[英]Cannot access python dictionnary keys in django template

这里已经解决了“简单”的问题。但是我没有找到解决方法。

所以这是个主意; 我有Anonymous1,Anymous2 ... Anymous3,他们通过电话号码接听电话和通话。 我想为他们每个人做一个这样的表:

Number | Calls | Communication time
2-xxx-x    1           01:00:00
3-xxx-x    23          00:30:00
total      24          01:30:00

呼叫数量,通信时间和总计都在视图中计算,因为它必须专用于此。 我有一个词典列表,其中包含所有电话号码,通话时间及其所有者。 它看起来像这样:

list = [{'number':2-xxx-x ,'owner':Anonymous1' ,'calls':1 ,'communication time':datetime object},...]

为什么要列出字典? 因为我正在按照文档中所述使用重组模板标签: https : //docs.djangoproject.com/fr/1.9/ref/templates/builtins/#regroup

我还制作了一个词典,其中仅包含呼叫总数,总通信时间和所有者。 我用它来计算每一列的总和。 它是这样的:

second_dict = {'Anonymous1':{'calls':24,'communication_time':datetime object}}

要访问它们,我在html代码中使用了循环,这是我遇到的问题。 要创建表,我要按其所有者对字典列表进行重新分组并执行循环,然后使用字典来创建:

{% regroup list by owner as owner_list %}

{% for owner in owner_list %}
<table class="display" cellspacing="0" style="position: relative; left: -250px;">
    <caption> {{owner.grouper}}</caption>
    <thead>
        <tr>
            <th> {% trans "Number" %} </th>
            <th> {% trans "Calls"%}</th>
            <th> {% trans "Communication time" %}</th>
        </tr>
    </thead>
    <tbody>
        {% for item in owner.list%}
        <tr>
            <td>{{item.number}}</td>
            <td>{{item.calls}}</td>
            <td>{{item.communication_time}}</td>   
        </tr>
        {% endfor %}
        <tr>
            {% with owner.list.0.owner as owner_name %}
            <td><b>{% trans "Total" %}</b></td>
            <td>{{second_dict.owner_name.calls}} </td>
            <td> {{second_dict.owner_name.communication_time}} </td>
            {% endwith %}
        </tr>
    </tbody>
</table>
{% endfor %}

正如您在代码中看到的那样,我要按照此处描述的内容,以所有者为键访问第二个字典值: https : //docs.djangoproject.com/en/dev/ref/templates/api/问题是...这根本不起作用! 我当时以为这是一个str / unicode问题,但是当在python视图中创建不同的字典时从一个移到另一个就没有任何改变。

任何人都知道如何解决这个问题?

您无法使用变量在模板的字典中进行查找,模板中的dict始终会将点后的内容视为字符串查找,就像second_dict['owner_name'] 您需要编写模板过滤器才能执行此操作。 有关如何编写自定义过滤器的信息,请参阅django文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM