Access Dictionary Keys in Django Template

There is no built-in way of accessing dictionary keys inside a Django template. We will therefore need to create a custom template tag to handle accessing dictionary keys, which is what this tutorial will cover.

 

Step 1

The first step is to create a directory called templatetags in the root of your app directory.

 

my_project/my_app/templatetags

 

Now create an empty __init__.py file in the app root.

 

my_project/my_app/__init__.py

 

Step 2

Create a new file called dict_key.py in the templatetags directory with the following code:

 

my_project/my_app/templatetags/dict_key.py
from django import template

register = template.Library()

@register.filter(name='dict_key')
def dict_key(d, key):    
   return d[key]

 

The dict_key function takes two arguments, the first is the dictionary and the second is the key name to access.

 

Step 3

Now we can load the custom tag and use it inside a template.

 

{% load dict_key %}

{{ i.map|dict_key:k }})

 

i.map is the dictionary and k is the key to look for.

 

Before this will work, you need to reload the Django server by running the following command in the terminal:

 

python manage.py runserver
django