Iterating through a dictionary of <Object, List> mappings. Django Tempates - python

I'm passing a django template , an argument like :
{'dict' : {Object0:[object1, object2, object3,.....], Object1:[object4, object5], ... } }
Is there anyway to iterate through that dictionary inside the template ?
Something like this wouldn't work :
{% for obj in dict %}
{% for objs in dict.obj %}
{# do sth here ... #}
{% endfor %}
{% endfor %}
Thanks

In Python, iterating through a dict just iterates through its keys. You want the values:
{% for obj in dict.values %}
{% for item in obj %}
{{ item }}
{% endfor %}
{% endfor %}
If you need both keys and values, you could use items:
{% for key, value in dict.items %}

Related

Django display a value from a dictionary within dictionary

I'm trying to display values from a dictionary within a dictionary in a template using django.
I have a dictionary like this in my views:
characters = {
"char1": {'name': "David",
'stars': 4,
'series': "All star"},
"char2": {'name': "Patrick",
'stars': 3,
'series': "Demi god"}
}
I can display the whole dictionary on the page, however I want to display only the 'name' and 'David' key:value pairs. I wrote the following in the template:
{% for char in characters %}
{% for key, value in char %}
{{ key }}: {{ value }}
{% endfor %}
{% endfor %}
However this doesn't show me anything. What is wrong with this double loop?
Thanks
You have to add .items when you loop through key value pairs.
See below (Python 3):
{% for char in characters.items %}
{% for c in char %}
name: {{ c.name }}
{% endfor %}
{% endfor %}
In Python 2 it would be .iteritems
{% for char in characters.iteritems %}
{% for c in char %}
name: {{ c.name }}
{% endfor %}
Thanks to kfarnell's help I finally managed to get this:
{% for character, params in characters.items %}
{{ params.name }}: {{ params.stars }}
{% endfor %}

How can I print a list with jinja2?

I'm trying to generate an HTML table with Jinja2. The data for the table is in an collections.OrderedDict where the keys are strings and the values are lists of strings.
I've tried to implement it using the following loops:
{% for key in table.keys() %}
{% for a_list in table[key] %}
{% for a_value in a_list %}
{{ a_value }}
{% endfor %}
{% endfor %}
{% endfor %}
Except in the Python console this works but in Jinja2 it dies with the error TypeError: 'int' object is not iterable
How do I iterate through a list in Jinja2?
You have one loop too many. table[key] is a list object, so looping over that gives you the values in the list:
{% for key in table.keys() %}
{% for a_value in table[key] %}
{{ a_value }}
{% endfor %}
{% endfor %}
Your extraneous loop tried to loop over the integer objects in your lists. Note that you don't need to loop over the keys() result; you can loop directly over the dictionary:
{% for key in table %}
{% for a_value in table[key] %}
{{ a_value }}
{% endfor %}
{% endfor %}
If you are not using the key in the loop, just loop directly over the values:
{% for list_value in table.values() %}
{% for a_value in list_value %}
{{ a_value }}
{% endfor %}
{% endfor %}

Iterate dictionary in django template

I have a dictionary
>>> filterdata
{u'data': [{u'filter': u'predictions', u'filtervalue': u'32', u'filterlevel': u'cltv', u'filtertype': u'>'}, {u'filter': u'profile', u'filtervalue': u"'TOMMY'", u'filterlevel': u'firstname', u'filtertype': u'='}]}
and i am using this to in django template
{% for c in filterdata.data %}
{{c}} ## print the current iterating dictionay
{% for d in c.items %}
{{ d.filtervalue }} ## does not print anything
{% endfor %}
{% endfor %}
any idea what i am doing wrong
You're iterating too much. d is the set of key-value pairs in the dict; filteritems is one of those keys, not an attribute of the pairs themselves. Remove that inner loop.
{% for c in filterdata.data %}
{{ c.filtervalue }}
{% endfor %}

dictionaries in django templates

I have a dictionary that could consist of the following values
images={'25/02/2014': {u'Observation': [<Image: Image object>]}}
that is
{
date:{title1:[obj1, obj2, obj3], title2:[obj1, obj2, obj3]},
date2:{title1:[obj1, obj2, obj3]},
}
and I want to access the values individually and eventually the object list for each title. My code was
{%for date in images%}
{%for title in images.date%} #equivalent to for title in images[date]:
{{date}} - {{title}}
{% for obj in images.date.title%} #equivalent to for obj in images[date][title]: but not sure
{{obj}}
{%endfor%}
{%endfor%}
{%endfor%}
but it won't work. It works in python for a dictionalry but not in django template. How can I access a dictionary?
You want to iterate on the (key, values) pairs instead:
{% for date, data in images.items %}
{% for title, images in data.items %}
{{date}} - {{title}}
{% for image in images %}
{{ image }}
{% endfor %}
{% endfor %}
{% endfor %}

django template - for loop over 2 querysets

I am getting 2 querysets from db:
all_locations = Locations.objects.all()[:5]
rating = Rating.objects.all()[:5]
return render_to_response('index.html',{'all':all_locations,'rating':rating},context_instance=RequestContext(request))
But I am stuck here, not knowing how to loop over these 2 querysets in one loop. this is being wrong:
{% if all and rating %}
{% for every in all and rating %}
{{every.locationname}}, {{every.rating_score}}
{% endfor %}
{% endif %}
You can try zip(all_locations, rating). It will produce a list of tuples. Then you can iterate over them in pairs. Here is an example: (demo)
all_locations = ['ca','ny','fl']
ratings = ['best','great','good']
for (l,r) in zip(all_locations,ratings):
print l+':'+r
Outputs
ca:best
ny:great
fl:good
I have also come across this problem. Now I've fixed it.
what I do is using
new=tuple(zip(queryset1,queryset2))
return render(request, 'template.html', {"n": new}).
in view.py.
In template.html, I use three for sentences which are list below.
{% for i in n %}
{% for j in i|slice:"0:1" %}
......operate queryset1
{% endfor %}
{% for z in i|slice:"1:2" %}
.....operate queryset2
{% endfor %}
{% endfor %}
It seems this method will fulfill your needs.
this might work:
{% with rating|length as range %}
{% for _ in range %}
{{ rating[forloop.counter] }}
{{ location[forloop.counter] }}
{% endfor %}
{% endwith %}
i'm not sure if rating|length will to the job... you might need to add rating|length|times' withtimes` filter defined as:
#register.filter(name='times')
def times(number):
return range(number)

Categories

Resources