简体   繁体   中英

Code doesn't work in template

My problem is basically the same code doesn't work in django template, but it works 'python'. Keys in results dict are strings and values are 'collections.Counter' type. I'm using Django 1.6.1. Here's the code

for k,v in results.items():
    for a,b in v.items():
        print a,':',b

Template:

{% for k,v in results.items %}
    {% for a,b in v.items %}
        {{ a }}, {{ b }}
    {% endfor %}
{% endfor %}

Error I'm getting is:

 'int' object is not iterable

and pointing to second for loop line. How can I fix it?

Sample:

for k,v in results.items():
    print k,v
    for a,b in v.items():
        print a,':',b
OUTPUT:
question1 Counter({u'1': 3, u'': 1, u'2': 1})
1 : 3
 : 1
2 : 1
question2 Counter({u'q': 3, u'': 1, u'w': 1})
q : 3
 : 1
w : 1
question3 Counter({u'a': 2, u'': 2, u's': 1})
a : 2
 : 2
s : 1

I reproduce it in a ./manage.py shell :

from django.template import Context, Template
from collections import Counter

t = Template('{% for k,v in results.items %}{% for a,b in v.items %}[{{ a }}, {{ b }}]{% endfor %}{% endfor %}')
c = Context({"results": {"question1": Counter({'1': 3, '': 1, '2': 1})}})
t.render(c)

And of course I obtained the same error. This is because items inside the for keyword is not a simple call to dict.items and do not support Counter .

Try to convert your Counter in a dict when you create the Context :

from django.template import Context, Template
from collections import Counter

t = Template('{% for k,v in results.items %}{% for a,b in v.items %}[{{ a }}, {{ b }}]{% endfor %}{% endfor %}')
c = Context({"results": {"question1": dict(Counter({'1': 3, '': 1, '2': 1}))}})
t.render(c)

You will obtain:

u'[1, 3][, 1][2, 1]'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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