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.




Now create an empty file in the app root.




Step 2

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


from django import template

register = template.Library()

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 %}

{{|dict_key:k }}) 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 runserver