How to look up a dictionary value with a variable in Django template

0 votes

The regular way to lookup a dictionary value in a Django template is {{ mydict.key1 }}, {{ mydict.key2 }}. What if the key is a loop variable? ie:

{% for item in list %} # where item has an attribute NAME
  {{ mydict.item.NAME }} # I want to look up mydict[item.NAME]
{% endfor %}
mydict = {"key1":"value1", "key2":"value2"}

mydict.item.NAME fails. How to fix this?

Aug 3, 2020 in Python by kartik
• 37,520 points
10,767 views

1 answer to this question.

0 votes

Hii @kartik,

Write a custom template filter:

from django.template.defaulttags import register
...
@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

(I use .get so that if the key is absent, it returns none. If you do dictionary[key] it will raise a KeyError then.)

usage:

{{ mydict|get_item:item.NAME }}

Hope it helps!!
Thank You!!

answered Aug 3, 2020 by Niroj
• 82,840 points

Related Questions In Python

0 votes
1 answer

How to do math in a Django template?

Hello @kartik, You can use the add filter: {{ object.article.rating_score|add:"-100" }} Thank ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,840 points
6,572 views
0 votes
1 answer

How to call function that takes an argument in a Django template?

Hello @kartik, You cannot call a function that ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,840 points
13,041 views
0 votes
1 answer

How to set up a PostgreSQL database in Django?

Hello @kartik, Steps that I use: - sudo apt-get ...READ MORE

answered Jun 30, 2020 in Python by Niroj
• 82,840 points
910 views
0 votes
1 answer

How to update date automatically after a value change in django?

Hello @kartik, Only change your pub_date if published has ...READ MORE

answered Jul 3, 2020 in Python by Niroj
• 82,840 points
9,747 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,840 points
2,521 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,840 points
1,592 views
0 votes
1 answer

How to output text from database with line breaks in a django template?

Hello @kartik, Use linebreaks or linebreaksbr filter: {{ text|linebreaks }} Or surround the text ...READ MORE

answered Jun 24, 2020 in Python by Niroj
• 82,840 points
13,569 views
0 votes
1 answer

How to access a dictionary element in a Django template?

Hello @kartik, Use Dictionary Items: {% for key, value ...READ MORE

answered Jul 3, 2020 in Python by Niroj
• 82,840 points
17,747 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP