Display JSON as template list in django - python

I have following JSON document:
{
"document": {
"section1": {
"item1": "Item1Value",
"item2": "Item2Value"
},
"section2": {
"item1": "Item1Value",
"item2": "Item2Value"
},
"section3": {
"item1": "Item1Value",
"item2": "Item2Value"
}
}
}
Which I want to display in my django template. This document will be dynamic, so I want to display each sections dynamically. I am passing parsed (by json.loads()) string to the template.
I tried something like:
{% for section in json.document %}
<div class="section">
<h4> {{ section|title }}:</h4>
<table class="table table-condensed">
{% for field in json.document.section %}
{{ field }} {# <---- THIS should print item1, item2... Instead, its printing "section1" letter by letter etc #}
{% endfor %}
</table>
</div>
{% endfor %}
But it doesn't printting section's items properly. Any help?

You can instead pass the dictionary to your template and access it by iterating over the values using dict.items in your template.
{% for key1,value1 in json.document.items %}
<div class="section">
<h4> {{ key1|title }}:</h4>
<table class="table table-condensed">
{% for key2,value2 in value1.items %}
{{ key2 }}
{% endfor %}
</table>
</div>
{% endfor %}
In your code above, it was printing "section1" letter by letter because you were not iterating over the values of the section1 key but on the section1 string itself. If you need to access the items in a dictionary, you need to use individual variables for keys and values and use dict.items.
For example, the below code would print the keys and values of the data dictionary in the template.
{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}

Related

How to properly unpack a nested dictionary in a django HTML template?

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>

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

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.

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