Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
989 views
in Technique[技术] by (71.8m points)

python - Sum in html template using template tag

I am trying to sum in HTML,but template tag return 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))

Template :

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>

Template tag:

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)

output :

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)

I am doing anything wrong here ?

can you please help me,how to return sum total using template tag here ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your template tag looks wrong. You have role_total as the parameter and then iterate through list_total (seemingly undefined) and from each dictionary in the list try getting the key list_sum which is also seemingly undefined.

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)

and calling it from the template at as <td>{{ list|running_total}}</td>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...