[Answer]-Code doesn't work in template

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]'
๐Ÿ‘คAndrea de Marco

Leave a comment