Open In App

Handle and Iterate Nested Dictionaries in Django Templates

Last Updated : 16 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

output-Gfg
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.


Next Article
Practice Tags :

Similar Reads