Django display a value from a dictionary within dictionary - python

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 %}

Related

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 %}

Django Template: key, value not possible in for loop

Error I get:
Need 2 values to unpack in for loop; got 1.
Here is my view:
class Index(View):
def get(self, request, slug):
test = {
1: {
'id': 1,
'slug': 'test-slug-1',
'name': 'Test Name 1'
},
2: {
'id': 2,
'slug': 'test-slug-2',
'name': 'Test Name 2'
}
}
context = {
'test': test
}
return render(request, 'wiki/category/index.html', context)
Here is my template:
{% block content %}
<div>
{{ test }}
<ul>
{% for key, value in test %}
<li>
{{ key }}: {{ value }}
</li>
{% endfor %}
</ul>
</div>
{% endblock %}
I also tried the template like:
{% block content %}
<div>
{{ test }}
<ul>
{% for value in test %}
<li>
{{ value }}: {{ value.name }}
</li>
{% endfor %}
</ul>
</div>
{% endblock %}
No error then, but {{ value }} shows key (which is fine), but {{ value.name }} shows nothing. While {{ test }} shows my dict.
Loop through the dictionary's items to get the keys and values:
{% for key, value in test.items %}
Not familiar with Django. However, by default, Python iterates over the keys for a dictionary. I am also going to assume you are using Python2. To get the values, you need to do:
{% for value in test.itervalues() %}
If you want both, you need to do:
{% for key, value in test.iteritems() %}
That will give you both the key and the value.

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 %}

How to iterate through a list of dictionaries in Jinja template?

I tried:
list1 = [{"username": "abhi", "pass": 2087}]
return render_template("file_output.html", list1=list1)
In the template:
<table border=2>
<tr>
<td>
Key
</td>
<td>
Value
</td>
</tr>
{% for dictionary in list1 %}
{% for key in dictionary %}
<tr>
<td>
<h3>{{ key }}</h3>
</td>
<td>
<h3>{{ dictionary[key] }}</h3>
</td>
</tr>
{% endfor %}
{% endfor %}
</table>
The above code is splitting each element into multiple characters:
[
{
"
u
s
e
r
...
I tested the above nested loop in a simple Python script and it works fine but not in Jinja template.
Data:
parent_list = [{'A': 'val1', 'B': 'val2'}, {'C': 'val3', 'D': 'val4'}]
in Jinja2 iteration:
{% for dict_item in parent_list %}
{% for key, value in dict_item.items() %}
<h1>Key: {{key}}</h1>
<h2>Value: {{value}}</h2>
{% endfor %}
{% endfor %}
Note:
Make sure you have the list of dict items. If you get UnicodeError may be the value inside the dict contains unicode format. That issue can be solved in your views.py.
If the dict is unicode object, you have to encode into utf-8.
As a sidenote to #Navaneethan 's answer, Jinja2 is able to do "regular" item selections for the list and the dictionary, given we know the key of the dictionary, or the locations of items in the list.
Data:
parent_dict = [{'A':'val1','B':'val2', 'content': [["1.1", "2.2"]]},{'A':'val3','B':'val4', 'content': [["3.3", "4.4"]]}]
in Jinja2 iteration:
{% for dict_item in parent_dict %}
This example has {{dict_item['A']}} and {{dict_item['B']}}:
with the content --
{% for item in dict_item['content'] %}{{item[0]}} and {{item[1]}}{% endfor %}.
{% endfor %}
The rendered output:
This example has val1 and val2:
with the content --
1.1 and 2.2.
This example has val3 and val4:
with the content --
3.3 and 4.4.
{% for i in yourlist %}
{% for k,v in i.items() %}
{# do what you want here #}
{% endfor %}
{% endfor %}
Just a side note for similar problem (If we don't want to loop through):
How to lookup a dictionary using a variable key within Jinja template?
Here is an example:
{% set key = target_db.Schema.upper()+"__"+target_db.TableName.upper() %}
{{ dict_containing_df.get(key).to_html() | safe }}
It might be obvious. But we don't need curly braces within curly braces. Straight python syntax works. (I am posting because I was confusing to me...)
Alternatively, you can simply do
{{dict[target_db.Schema.upper()+"__"+target_db.TableName.upper()]).to_html() | safe }}
But it will spit an error when no key is found. So better to use get in Jinja.
**get id from dic value. I got the result.try the below code**
get_abstracts = s.get_abstracts(session_id)
sessions = get_abstracts['sessions']
abs = {}
for a in get_abstracts['abstracts']:
a_session_id = a['session_id']
abs.setdefault(a_session_id,[]).append(a)
authors = {}
# print('authors')
# print(get_abstracts['authors'])
for au in get_abstracts['authors']:
# print(au)
au_abs_id = au['abs_id']
authors.setdefault(au_abs_id,[]).append(au)
**In jinja template**
{% for s in sessions %}
<h4><u>Session : {{ s.session_title}} - Hall : {{ s.session_hall}}</u></h4>
{% for a in abs[s.session_id] %}
<hr>
<p><b>Chief Author :</b> Dr. {{ a.full_name }}</p>
{% for au in authors[a.abs_id] %}
<p><b> {{ au.role }} :</b> Dr.{{ au.full_name }}</p>
{% endfor %}
{% endfor %}
{% endfor %}

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

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 %}

Categories

Resources