How to Lookup Dictionary Value with Key in Django Template

This tutorial is all about looking into a dictionary value using a key in Django Template. This task will be accomplished by creating a dictionary in the views.py file and then rendering an HTML template, passing the dictionary as arguments, we will use a key to check the value at that particular index.

Before heading towards the snippet part, let’s start our project and our app.

  1. Create a project usingdjango-admin startproject projet
  2. Start an app using python manage.py startapp app
  3. Create an HTML Template named as page.html inside your project. Make sure it is in directory where manage.py is present.

Define a path

Move to the urls.py to define a path through which we can see our output screen.

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.test,name="test")
]

This is the URL part where we will navigate to see our template.

Create a function in views.py

We will create a function named test which will have dictionary and it will render a page that is saved as page.html and will pass dictionary as an argument which will be further displayed using a for loop.

def test(request):
    data = {'a': 1, 'b': 2,'c':3 }
    return render(request, 'page.html',{'data':data})

This is the dictionary with some keys and the values. We need to display it using for loop.

Create a HTML page

Open your page.html and write a code to display the value of key using a for loop as-

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Django look up dictionary</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    {% for key, value in data.items %}
    Key{{ key }} Value{{ value }}<hr>
    
{% endfor %}
 
</html>

This is code for HTML where we will use a for loop to display a key and its value.

Run your server to Lookup Dictionary Value with Key in Django Template

The last step is to run your server. You will get an output screen like-

How to Lookup Dictionary Value with Key in Django Template

Here you can see that we have a key and its value. For example, we have key a and its value is 1, the same is displayed.

Leave a Reply

Your email address will not be published.