Md. Imrul Hasan
Md. Imrul Hasan

Reputation: 29

How to get dictionary value of a key inside a loop in Django Template?

views.py

def get(self, request, *args, **kwargs):
    domains = Domain.objects.all()
    context['domains'] = domains

    domain_dict = {}
    # ..........
    # ..........some codes here for domain_dict dictionary
    print(domain_dict)
    context['domain_dict'] = domain_dict
    return render(request, self.response_template, context)

{4: '', 3: '', 1: '', 5: '', 7: '', 2: '', 6: 'Are you a candidate for the engineering admission '}

templates.html

<div class="col-md-8">
    <div class="tab-content">
        {% for domain in domains %}
            {% with domain_id=domain.id %} 
            <div class="tab-pane container p-0 {% if forloop.first %} active {% endif %}" id="services{{domain.id}}">
                <div class="img" style="background-image: url('static/counsellor/images/service-1.png');">
                </div>  
                <h3><a href="#">Name: {{domain.name}} ID: {{domain_id}}</a></h3>
                <p>{{domain_dict.6}}</p>
            </div>
            {% endwith %}
        {% endfor %}
    </div>
</div>

In the above template I use <p>{{domain_dict.6}}</p>. domain_dict.6 to find the value of key 6. It returns perfectly. Outputs: Are you a candidate for the engineering admission.

<div class="col-md-8">
    <div class="tab-content">
        {% for domain in domains %}
            {% with domain_id=domain.id %} 
            <div class="tab-pane container p-0 {% if forloop.first %} active {% endif %}" id="services{{domain.id}}">
                <div class="img" style="background-image: url('static/counsellor/images/service-1.png');">
                </div>  
                <h3><a href="#">Name: {{domain.name}} ID: {{domain_id}}</a></h3>
                <p>{{domain_dict.domain_id}}</p>
            </div>
            {% endwith %}
        {% endfor %}
    </div>
</div>

In the above template I use <p>{{domain_dict.domain_id}}</p>. domain_dict.domain_id to find the value of key domain_id. It returns null. Here domain_id = 4,3,1,6,5,7,2 Outputs: null

How can I return the value of a key of the dictionary here?

Upvotes: 0

Views: 128

Answers (1)

OlegТ
OlegТ

Reputation: 181

I've recently run into the same problem. Here is example of the solution.

Say, we have tuple

people = ('Vasya', 'Petya', 'Masha', 'Glasha')

and dictionary with their status:

st = {
    'Vasya': 'married',
    'Petya': 'divorced',
    'Masha': 'married',
    'Glasha': 'unmarried'
}

We transfer these to our template as context of corresponding view:

context['people'] = people
context['st'] = st

If we write in template

{% for person in people %}
    {{ person }} is {{ st.person }}
{% endfor %}

then it won't work. Well, 'person' will be displayed, but data from dictionary will not. Because :

Note that bar in a template expression like {{ foo.bar }} will be interpreted as a literal string and not using the value of the variable bar, if one exists in the template context.

The solution of the problem is either to use another data structure or to use custom filter in the template. The idea of the latter is to add a filter to your dictionary in the template, which takes current value of person and returns corresponding value of the dictionary. To do this,

  1. create in the folder with your app new folder templatetags,
  2. write the path to this new folder in settings.py,
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            ...,
            os.path.join(BASE_DIR, 'your_app/templatetags'),
        ],
       ...
    }
  1. inside the templatetags create new file, say, filter.py with our new filter called dict_value:
from django import template

register = template.Library()

@register.filter
def dict_value(d, key):
    return d[key]
  1. go back to your template and load newly created filter somewhere in first lines:
{% load filter %}
  1. rewrite you template code like this:
{% for person in people %}
    {{ person }} is {{ st|dict_value:person }}
{% endfor %}

Now it works as needed.

Upvotes: 1

Related Questions