sus*_*ush 2 python django django-templates django-template-filters
我想在HTML中求和,但模板标签返回0,
View.py
def gen_Report(request):
### query returns below output
list=[{'total': 1744, 'user': u'x'}, {'total': 13, 'user': u'y'}, {'total': 126, 'user': u'z'}, {'total': 46, 'user': u'm'}, {'total': 4, 'user': u'n'}, {'total': 8, 'user': u'o'}, {'total': 3, 'user': u'p'}]
return render_to_response('user.html', locals(),
context_instance = RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
模板:
user.html
{% load temptags %}
<table id="myTable" class="tablesorter">
<thead>
<tr>
<th>S.No</th>
<th>role</th>
<th>Count</th>
</tr>
</thead>
{% for fetch in list %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{fetch.user}}</td>
<td>{{fetch.total}}</td>
{% endfor %}
<td>{{ list.total|running_total}}</td>
<tr>
</table>
Run Code Online (Sandbox Code Playgroud)
模板标签:
from django.template import Library
register = Library()
@register.filter
def running_total(list_total):
return sum(d.get('list_sum') for d in list_total)
Run Code Online (Sandbox Code Playgroud)
输出:
S.No user Count
1 x 1744
2 y 13
3 z 126
4 m 46
5 n 4
6 o 8
Sum------------------> 0 (it returns zero)
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么?
你可以帮助我,如何在这里使用模板标签返回总和?
您的模板标记看起来不对.你有role_total参数,然后迭代list_total(看似未定义),并从列表中的每个字典尝试获取list_sum看似未定义的键.
from django.template import Library
register = Library()
@register.filter
def running_total(your_dict_list):
return sum(d['total'] for d in your_dict_list)
Run Code Online (Sandbox Code Playgroud)
并在as模板中调用它 <td>{{ list|running_total}}</td>
| 归档时间: |
|
| 查看次数: |
8179 次 |
| 最近记录: |