Rishi
Rishi

Reputation: 97

For Loop in Django template for nested dictionaries

I have a model with the following fields:

I want to be able to present this data as follows in my template:

  • tag1: -- Name1 -- Name2
  • tag2: -- Name3 -- Name4, etc.

In order to do this, in my views.py function, I am first making a list of all the values within tag, and then using this list to put together a dictionary that groups all the instances as per the individual values in the list.

For example, if this were a to-do app, the list would be tags such as ['home', 'office', 'hobby'...] and the final dictionary would look like:

{'home': <QuerySet [<Task: Buy Milk>, <Task: Buy Food>]>, 'hobby': <QuerySet [<Task: Play guitar>, <Task: Read books>]>, 'office': <QuerySet [<Task: Send email>, <Task: Schedule Meeting>]>}

Once I have this dictionary of dictionaries, I pass it on to template as context.

def bytag(request):
    value_list = Task.objects.values_list('tag', flat=True).distinct()
    group_by_value = {}
    for value in value_list:
        group_by_value[value] = Task.objects.filter(tag=value)
    context = {'gbv': group_by_value}

    return render(request,'tasks/bytag.html', context)

I have tried out these queries in the shell, and they work fine. So in the template, I am trying the following to loop over the data:

{% block content %}

{% for item in gbv %}
{{ item }}

{% for stuff in gbv[item] %}
{{stuff.name}}

{% endfor %}
{% endfor %}

{% endblock content %}

While the first for-loop works, Django doesn't seem to allow me to access individual elements in the second dictionary by specifying a key thus: gbv[item] and I get a

Template syntax error: Could not parse the remainder: '[item]' from 'gbv[item]'

What am I doing wrong?

Upvotes: 1

Views: 354

Answers (2)

Rishi
Rishi

Reputation: 97

This is what worked:

{% for key, values in gbv.items %}
    <h3>{{key}}</h3>
 
    {% for value in values %}
        {{value.name}}
        
    {% endfor %}
{% endfor %}

The two errors:

  1. I had to add .items as pointed out by @Mayank Gupta
  2. The above actually returns a list and not a dictionary. Hence, 'key, value' was throwing up an error. I only figured this out after printing out the output of the first loop (guess I should have done that earlier - lesson learnt!)

Upvotes: 0

Mayank Gupta
Mayank Gupta

Reputation: 41

You can use .items to iterate on a dictionary.

{% for key, value in gbv.items %}
     {% for key2, value2 in value.items %}
           {{key2}}, {{value2}}
     {% endfor %}
{% endfor %}

Upvotes: 1

Related Questions