Django template: access inner dictionary - django

A newbie django template question, hope to get some pointers.
I'm passing back a dictionary to render to html for a page. The structure of the dictionary is like the following:
dic:{
"names":["name1", "name2", "name3"],
"names1":{
"addresses":["address1","address2","address3"],
"key2":[......]
......
}
"name2":{......}
}
How do I access the inner dictionaries? The only way to know the keys for those inner dictionaries is from the list, but I was unable to iterate through values pointed by key "names" and use that value as a key to get the other dictionary. I have looked into writing customer filters/tags but not sure exactly how to proceed.

Use items, from django docs:
{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}
I tested it with your example:
In template:
<ul>
{% for l1_key, l1_value in dic.items %}
<li>{{ l1_key }}:
<ul>
{% for l2_key, l2_value in l1_value.items %}
<li>{{ l2_key }}: {{ l2_value }}</li>
{% empty %}
<li>{{ l1_value }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
This will output something like:
- name2:
- address: [1, 2, 3]
- names:
- ['name1', 'name2', 'name3']
- names1:
- key2: [1, 2]
- addresses: ['address1', 'address2', 'address3']
items return a list of tuples formed by (key, value)
I used this dic (fix minor problems in your example):
dic = {
"names":["name1", "name2", "name3"],
"names1":{
"addresses":["address1","address2","address3"],
"key2":[1,2]
},
"name2":{'address':[1,2,3]}
}

Related

Django template jinja for loop

Can someone suggest me how to iterate a dictionary in django template?
dic1={5: ['jaw replacement - 23-Jun-2020 (16:20:09.164240)', 'jaw replacement done - 23-Jun-2020 (16:20:51.158085)', 'jaw replacement done,almost done - 23-Jun-2020 (16:25:40.066955)', 'jaw replacement done,almost done 1 - 23-Jun-2020 (16:27:00.355605)', 'jaw replacement done,almost done 2 - 23-Jun-2020 (16:31:35.111660)']}
this is the context i am passing
i need something like this in template
for i in dic1:
print(i)
list1=dic1[i]
for k in list1:
print(k)
{% for i in notes %}
{% with list1=dic1[i] %}
{{list1}}
{% endwith %}
{% endfor %}
This is not working.
Lets say your data is -
dic1 = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }
You can use the data.items() method to get the dictionary elements. Note, in django templates we do NOT put (). Also some users mentioned values[0] does not work, if that is the case then try values.items.
<table>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
{% for key, values in dic1.items %}
<tr>
<td>{{key}}</td>
{% for v in values[0] %}
<td>{{v}}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
I hope It helps you.
In normal Python you would normally access keys and values by using the items() method on a dictionaty.
For example given the dictionary
some_dic = {'1': 'Hello', '2': 'World'}
You should be able to access this by doing the following:
for key, value in some_dic.items():
print(key, value)
You can follow this same principle in Django templates and simply omit the '()' as follows:
{% for key, value in some_dic.items %}
<h1>Key: {{ key }}</h1>
<h1>Value: {{ value }}</h1>
{% endfor %}
you can pass dic1 one directly to the template from view and iterate through dictionary in template \
in view
return render(request, 'template.html',{'dic1':dic1})
#intemplate.html
{% for key, value in dic1 %}
<tr>
<td> Key: {{ key }} </td>
{% for value_in_array in value %}
<td> Value: {{ value }} </td>
{% endfor %}
</tr>
{% endfor %}

Iterate specific dictionary values in django template

When i receive a associative array namely dictionaries in django template which as follows
"receivable_aging": {
"age5": 235114.91999999998,
"age4": 235114.91999999998,
"age3": 0,
"age2": 0,
"age1": 0 }
I tried to print like this
{% for key, value in receivable_aging.items %}
{{ value }}
{% endfor %}
I want to print age1 to age4 in ascending order. How can I achieve this without if or minimal steps.
Sort items in your views.py:
return render_to_response('page.html',
{'receivable_aging': sorted(receivable_aging.items())})
Then print them in template:
{% for key, value in receivable_aging %}
{{ value }}
{% endfor %}
Hope it helped.

Django template variables as key for a list

I'm coming from this question Use variable as dictionary key in Django template
i've this context created in my view:
{'cats': {'LIST1': ['a','b','c'], 'LIST2': ['aa','bb','cc','dd'], 'LIST3': ['f','g']}}
what i want to do is to print the list title and then all the items, something like
LIST1:
- a
- b
- c
for all the lists, so i did this in my template
{% for l_name, l in cats %}
{{ l_name }}
{%for lv in l %}
{{ lv }}
{% endfor %}
{% endfor %}
and this prints only the list names, without printing out the list. where's the mistake?
thanks
If you want to iterate over keys and values, you can use:
{% for name, lst in cats.iteritems %}
....
{% endfor %}
This just calls the iteritems method of a dictionary, which returns an iterator over a list of 2-tuples.
Django's {% for %} tag documentation has some nice example of this too.
Just for the record, the problem is how the data are created. so instead of
{'cats': {'LIST1': ['a','b','c'], 'LIST2': ['aa','bb','cc','dd'], 'LIST3': ['f','g']}}
i need a list of touple so:
{'cats': [('LIST1', ['a','b','c']), ('LIST2', ['aa','bb','cc','dd']), ('LIST3', ['f','g'])]}

django templates accessing a dict value based on key

in my views.py i obtain 5 dicts, which all are something like {date:value}
all 5 dicts have the same length and in my template i want to obtain some urls based on these dicts, with the common field being the date - as you would do in an sql query when joining 5 tables based on a common column
in python you would do something like:
for key, value in loc.items():
print key, loc[key], ctg[key], sctg[key], title[key], id[key]
but in django templates all i could come up with is this:
{% for lock, locv in loc.items %}
{% for ctgk, ctgv in ctg.items %}
{% for subctgk, subctgv in subctg.items %}
{% for titlek, titlev in titlu.items %}
{% for idk, idv in id.items %}
{% ifequal lock ctgk %}
{% ifequal ctgk subctgk %}
{% ifequal subctgk titlek %}
{% ifequal titlek idk %}
<br />{{ lock|date:"d b H:i" }} - {{ locv }} - {{ ctgv }} - {{ subctgv }} - {{ titlev }} - {{idv }}
.... {% endifequals & endfors %}
which of course is ugly and takes a lot of time to be rendered
right now i am looking into building a custom tag, but i was wondering if you guys have any feedback on this topic?
Sounds to me like you need to use something other than aligned dicts. How about a dict of a small class, which contains the things you want:
class MyThing:
def __init__(self, loc, ctg, sctg, title, id):
self.loc = loc
self.ctg = ctg
self.sctg = sctg
self.title = title
self.id = id
Would that make your template code a bit less painful? (Apologies if I've misunderstood the problem - I'm having a hard time following your nested ifs!).
Django templates should try to resolve variables with dot as a dictionary lookup (if varaible is an dictionary). So ctg.key equals to ctg[key]. Did you try this:
{% for key, value in loc.items %}
{{ key|date:"d b H:i" }} - {{ value }} - {{ ctg.key }} - {{ subctg.key }} - {{ title.key }} - {{ id.key }}

How to iterate over nested dictionaries in django templates

I'm not sure the most efficient way to iterate over my nested dictionaries to print a matrix of the total and good values for every fruit for each date. Take for instance the two lists and dictionary below:
fruits = ['apples','oranges','bananas']
harvest_dates = ['2011-07-23','2011-07-22','2011-07-21']
harvest_data = {
'apples': {
'2011-07-23': {
'total': 100,
'good': 80},
'2011-07-22': {
'total': 97,
'good': 92},
'2011-07-21': {
'total': 90,
'good': 85}
},
'oranges': {
'2011-07-23': {
'total': 86,
'good': 82},
'2011-07-22': {
'total': 90,
'good': 75},
'2011-07-21': {
'total': 92,
'good': 92}
},
'bananas': {
'2011-07-23': {
'total': 10,
'good': 9},
'2011-07-22': {
'total': 12,
'good': 11},
'2011-07-21': {
'total': 9,
'good': 9}
}
}
I can easily do this in python:
for fruit in fruits:
for day in harvest_dates:
print "harvest: %s" % harvest_data[fruit][day]['total']
print "good crop: %s" % harvest_data[fruit][day]['good']
But I don't know how to access this data in django templates. I had been trying something such as:
{% for fruit in fruits %}
...
{% for day in harvest_dates %}
...
{{ harvest_data.fruit.day.total }}
{{ harvest_data.fruit.day.good }}
...
{% endfor %}
{% endfor %}
But it's simply not working.
{% for fruit in fruits %}
{{ harvest_data.fruit }} <--- this does not exist
{{ harvest_data[fruit] }} <--- this does not work
{% endfor %}
I'm a complete amateur and I'm probably going about this all wrong, but I've Google'd quite a bit and it's not clear to me what the best approach to getting the data I want is.
Since you're familiar with python, the following is logically how you would want to iterate through your dictionary in a Django template:
for key,value in harvest_data.items():
... print key
... for key2,value2 in value.items():
... print key2
... for key3,value3 in value2.items():
... print "%s:%s"%(key3,value3)
In your template, this translates as follows:
{% for key, value in harvest_data.items %}
{{ key }} <br>
{% for key2,value2 in value.items %}
{{ key2 }} <br>
{% for key3, value3 in value2.items %}
{{ key3 }}:{{ value3 }} <br>
{% endfor %}
{% endfor %}
{% endfor %}
The Django docs actually briefly include an example of how to iterate through dictionaries when describing how the for template tag works:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
as rolling stone says thats the way to iterate over dictionaries in templates, i would only change the key, value keywords for different keywords in every iteration like this:
{% for key, value in harvest_data.items %}
{{ key }} <br>
{% for key2,value2 in value.items %}
{{ key2 }} <br>
{% for key3, value3 in value2.items %}
{{ key3 }}:{{ value3 }} <br>
{% endfor %}
{% endfor %}
{% endfor %}
just for the sake of clarity :)
And if you want to line up your values i would suggest you use another data structure where you can sort by date, for example a something like this:
{ 'oranges' : [(date1, value1), (date2,value2)] ...}
Try to do the least possible operations in your templates, so dont do a sort or nested if's if you dont have to
Really old question, but I will add my 1.5c.
This is a good use case of the regroup tag (https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#regroup) and a bit of data refactoring:
Have your data as a simple list of data points:
harvest_data = [
{'fruits': 'apples', 'date': '2011-07-23', 'total': 100, 'good': 80},
# ...
]
In your template, group by the chosen dimension(s):
{% regroup harvest_data by fruits as data_by_fruits %}
{% for data in data_by_fruits %}
<h1>{{ data.grouper }}</h1> # 'apples'
{% regroup data.list by date as data_by_fruits_date %}
{% for data_1 in data_by_fruits_date %}
<h2>{{ data_1.grouper }}</h2> # '2011-07-23'
{% for datapoint in data_1.list %}
total: {{ datapoint.total }} <br/>
good: {{ datapoint.good }} <br/>
{% endfor %}
{% endfor %}
{% endfor %}