"简单"这里的问题已经在一个视图中得到解决......但我没有办法解决这个问题。
所以这就是这个想法;我有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视图中创建不同的字典时,从一个移到另一个并没有改变任何东西。
任何人都有提示如何解决这个问题?
答案 0 :(得分:1)
你不能使用变量在模板中的字典中进行查找,模板中的dict总是将点之后的内容视为字符串查找,如second_dict['owner_name']
。您需要编写模板过滤器来执行此操作。在this上查看django doc。