Handle and Iterate Nested Dictionaries in Django Templates
Last Updated :
16 Aug, 2024
Django templates offer various tags and filters to work with data. they are designed to readable and expressive. To iterate through a dictionary which contains a dictionary itself as a Value we can use the " { % for % } " template tag to iterate over dictionary that contains dictionary. But Django templates don't support nested dictionary iterations directly. So, we'll need to ensure that the data is passed correctly from the view and may use custom template filters or tags if necessary.
Iterate using For-Loop in Django Templates
1. Access Dictionary in your Template: The dictionary you want to loop through must be available in the template context. You can pass it from your views.
2. Utilize the Template tag " { % for % } ": This template tag is used to loop over data in Django templates. And to loop over a dictionary containing a dictionary, you can nest it within your HTML structure.
<ul>
{% for student, grade in students_grades.items %}
<li>{{ student }}: {{ grade }}</li>
{% endfor %}
</ul>
In the above example, we use {% for student, grade in students_grades.items %} this line to loop over the students grades, where key are the students and their values are their grades.
3. Display Student Grades:
Withing the loop, we can access the student(key) and grades(value) variable to display the student's student-grades (key-value) pair together.
Code Example
In IDE, we first create a view with name 'data_view()' and then write the code mentioned below according to our needs. Then create a html template 'my_template.html' in the templates folder inside our directory in which we created all the files.
Views.py: In the code we have dictionary inside dictionary or we can say nested dictionary, where languages is outer dictionary and contains inner dictionary with three key ("python", "javascript", "java") and their values inside it.
Python
from django.shortcuts import render
def data_view(request):
languages = {
'Python': {
'Use Case': 'Web Development, Data Science, Automation',
'Description': 'A versatile, easy-to-learn,simple to understand programming language.'
},
'JavaScript': {
'Use Case': 'Web Development, Mobile App Development',
'Description': 'The Scripting language of the web, used for interactive websites.'
},
'Java': {
'Use Case': 'Enterprise Applications, Android Development',
'Description': 'A robust, platform-independent, mostly used language'
}
}
context = {'languages': languages}
return render(request, 'myapp/my_template.html', context=context)
In your template, you can iterate through this dictionary as follows:
- HTML Structure: This code provides a basic HTML structure with Django template tags in it .
- Django template tags: The {% for %} loop is used to iterate over the outer dictionary ('languages') and the inner dictionary ('details').
- Dynamic Content: The template dynamically generates the list of coding languages and their details by iterating through them one by one.
HTML
<!-- template.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Coding Languages</title>
</head>
<body>
<h2>Coding Languages</h2>
<ul>
{% for language, details in languages.items %}
<li><strong>{{ language }}</strong></li>
<ul>
{% for key, value in details.items %}
<li>{{ key }}: {{ value }}</li>
{% endfor %}
</ul>
{% endfor %}
</ul>
</body>
</html>
Output
The output will look like this Breakdown of output:
- Main Heading: Coding Languages will be displayed as a level 2 heading "<h2>Coding Languages</h2>" because of this in html file.
- List of Languages: Each language as a strong item in unordered list is listed <li><strong>{{ language }}</strong></li> because of this line.
- Sub-list: Each language has a nested unordered list showing its "Use Case" and "Description" details as Key:Value Pair,<ul> {% for key, value in details.items %} <li>{{ key }}: {{ value }}</li> {% endfor %} </ul>. because of this tags and django template provided between them.
- The HTML code in the template fetches and displays the data provided by the views.py file.
- Rendering the Template: The Data from "views.py" is sent to the template.html when the view function is called. Django's rendering engine takes the 'Context' dictionary and inserts the data into the template. which then visible in the browser when we run html code, in the html defined tags format.
Conclusion
Using Django Template to iterate over the dictionary which itself contains another dictionary as the value, allows us to effectively display complex data structures in a more clean and organized manner as it uses key: Value Pair structure. By leveraging nested loops, we can dynamically display multi-level data, making easier to manage and present information hierarchical configurations, detailed reports, or any data-driven content. To build a robust and scalable web applications where flexibility is important and because of more flexible it is more easier to maintain and extend our codebase in future.
Similar Reads
Concatenate Strings in Django Templates
Concatenating strings in Django templates can be achieved through several methods, including using built-in filters, formatting, and custom template tags. Each method has its use cases, and the choice depends on your specific needs. Whether you use simple filters for straightforward concatenation or
3 min read
How to Add Data from Queryset into Templates in Django
In this article, we will read about how to add data from Queryset into Templates in Django Python. Data presentation logic is separated in Django MVT(Model View Templates) architecture. Django makes it easy to build web applications with dynamic content. One of the powerful features of Django is fet
3 min read
Django Templates Directory Structure Explained
Django templates allow us to define the structure and layout of HTML pages. But to render the templates, Django needs to know where to locate and load them. In this article, we will explain the path that Django uses for locating and loading templates, how we can customize it, and the different ways
4 min read
Render a HTML Template as Response - Django Views
A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This article revolves around how to render an HTML page from Django using views. Django has always been known for its app structure and ability to manage applications easily. Let's di
3 min read
How to Access a Dictionary Element in a Django Template?
Accessing dictionary elements in Django templates can be accomplished through various methods, including direct access using dot or bracket notation, handling missing keys with default values or conditional checks, and utilizing custom template filters and tags for advanced use cases. Understanding
3 min read
Access Constants in settings.py from Templates in Django
Django is a popular web framework known for its simplicity and powerful features, enabling developers to build robust web applications quickly. One of the essential components of a Django project is the settings.py file, where configuration constants such as database settings, static files, and othe
4 min read
How to create Custom Template Tags in Django ?
Django offers a variety of built-in template tags such as {% if %} or {% block %}. However, Django also allows you to create your own template tags to perform custom actions. The power of custom template tags is that you can process any data and add it to any template regardless of the view executed
4 min read
How to Check for Last Loop Iteration in Django Template
Iterating over lists or querysets is a common task when working with Django templates. Sometimes, we may need to perform a specific action or modify the output during the last iteration of a loop. Unlike in Python, where checking for the last iteration is straightforward using loop indices, Django t
5 min read
Iterate over a dictionary in Python
In this article, we will cover How to Iterate Through a Dictionary in Python. To Loop through values in a dictionary you can use built-in methods like values(), items() or even directly iterate over the dictionary to access values with keys. How to Loop Through a Dictionary in PythonThere are multip
6 min read
how to use validate_comma_separated_integer_list in django
A validator is a callable that takes a value and raises a ValidationError if it doesnât meet the criteria. Validators can be useful for re-using validation logic between different types of fields. In this article, we will learn how to use 'validate_comma_separated_integer_list' validator in Django.
4 min read