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 %}
Related
So I was able to figure out how to unpack a dictionary keys and values on to a HTML template, but I am a bit confused as to how to unpack if if a dictionary value is a QuerySet. For example I passing in all the timeslots of the given user into the dictonary. How can I unpack the attributes of the TimeSlot QuerySet for each timeslot such as the start time and end time?
This is my HTML Template:
<table>
{% for key, value in user_info.items %}
{% for key2,value2 in value.items %}
<tr>
<td>{{key2}}</td>
<td>{{value2}}<td>
</tr>
{% endfor %}
<br>
{% endfor %}
</table>
My function in views.py
def check_food_availibility(request):
food = FoodAvail.objects.all()
timeslots = TimeSlot.objects.all()
users_dict = {}
for i in range(len(user_info)):
user = {
"author": None,
"food_available": None,
"description": None,
"timeslot": None
}
user["author"] = user_info[i].author.username
user["food_available"] = user_info[i].food_available
user["description"] = user_info[i].description
if TimeSlot.objects.filter(time_slot_owner=user_info[i].author):
user["timeslot"] = TimeSlot.objects.filter(time_slot_owner=user_info[i].author)
users_dict[user_info[i].author.username] = user
return render(request, "food_avail/view_food_avail.html", {"user_info": users_dict})
This is how it shows up currently:
try this
<table>
{% for key, value in user_info.items %}
{% for key2,value2 in value.items %}
<tr>
<td>{{key2}}</td>
{% if key2 == 'timeslot' %}
<td>
{% for i in value2 %}
i.start_time <-> i.end_time // just an example put your field here
{% endfor %}
</td>
{% else %}
<td>{{value2}}<td>
{% endif %}
</tr>
{% endfor %}
<br>
{% endfor %}
</table>
I am rendering a queryset on views.py like this:
person = MyDict.objects.filter(search_description = name)
return render(request,'myPage/find.html',{'person':person})
Its rendering like this:
person=[{
'gender': 'male',
'description': ['24', 'Student', 'NY']
}]
If i apply the following code on my html:
{% for item in person %}
{{ item.description }}
{% endfor %}
It returns as ['24', 'Student', 'NY']
But I want to view as like this:
24
Student
NY
How to do it???
You can use join template tag of django
{{ item.description|join:"<br>" }}
You nee to make templatetags for check value type is list or not.
templatetags code:
from django import template
register = template.Library()
#register.simple_tag
def is_list_type(data):
return isinstance(data, list)
html code:
{% load <templatetag file name> %}
{% for item in person %}
{% is_list_type item as result %}
{% if result %}
{% for value in item %}
{{value}} <br>
{% endfor %}
{% else %}
{{ item}}<br>
{% endif %}
{% endfor %}
Output:
male
24
Student
NY
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 %}
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)
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 %}