Django

Demonstrate Multiple Context Variables and Variable Lookup in Django Templates

๐Ÿ“Œ Introduction

In Django templates, we can:

  • Pass multiple variables from view
  • Access them using template syntax
  • Understand how Django resolves variables (lookup mechanism)

๐Ÿ‘‰ Variable lookup follows this order:

  1. Dictionary
  2. Object attribute
  3. List index

๐ŸŽฏ Program Statement

๐Ÿ‘‰ Demonstrate multiple context variables and variable lookup inside templates.


โš™๏ธ Step 1: Create View


๐Ÿ“ File: views.py

๐Ÿ”น Path:

myproject/myapp/views.py

๐Ÿ”น Code:

from django.shortcuts import render

def demo_context(request):

    # Simple variable
    name = "Juhi"

    # List
    marks = [78, 85, 90]

    # Dictionary
    student = {
        "course": "MCA",
        "year": "2nd Year"
    }

    # Nested dictionary (for lookup)
    data = {
        "student": {
            "name": "Aman",
            "age": 22
        }
    }

    return render(request, 'demo.html', {
        'name': name,
        'marks': marks,
        'student': student,
        'data': data
    })

๐Ÿง  Explanation

We passed:

  • String โ†’ name
  • List โ†’ marks
  • Dictionary โ†’ student
  • Nested dictionary โ†’ data

โš™๏ธ Step 2: URL Mapping


๐Ÿ“ File: urls.py

๐Ÿ”น Path:

myproject/myproject/urls.py

๐Ÿ”น Code:

from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
path('admin/', admin.site.urls),
path('demo/', views.demo_context),
]

โš™๏ธ Step 3: Create Template


๐Ÿ“ File: demo.html

๐Ÿ”น Path:

myproject/templates/demo.html

๐Ÿ”น Code:

<!DOCTYPE html>
<html>
<head>
<title>Context Demo</title>
</head>
<body>

<h1>Multiple Context Variables</h1>

<!-- Simple variable -->
<p>Name: {{ name }}</p>

<hr>

<!-- List access -->
<h3>Marks:</h3>
<p>First Mark: {{ marks.0 }}</p>
<p>Second Mark: {{ marks.1 }}</p>

<ul>
{% for m in marks %}
<li>{{ m }}</li>
{% endfor %}
</ul>

<hr>

<!-- Dictionary access -->
<h3>Student Info:</h3>
<p>Course: {{ student.course }}</p>
<p>Year: {{ student.year }}</p>

<hr>

<!-- Nested lookup -->
<h3>Nested Data:</h3>
<p>Name: {{ data.student.name }}</p>
<p>Age: {{ data.student.age }}</p>

</body>
</html>

โš™๏ธ Step 4: Run Server

python manage.py runserver

๐ŸŒ Step 5: Output

๐Ÿ‘‰ http://127.0.0.1:8000/demo/


โœ… Output:

Name: Juhi

Marks:
First Mark: 78
Second Mark: 85
โ€ข 78
โ€ข 85
โ€ข 90

Student Info:
Course: MCA
Year: 2nd Year

Nested Data:
Name: Aman
Age: 22

๐Ÿง  Variable Lookup Explained ๐Ÿ”ฅ


โœ… 1. Dictionary Lookup

{{ student.course }}

๐Ÿ‘‰ Looks for key "course"


โœ… 2. List Lookup

{{ marks.0 }}

๐Ÿ‘‰ First element


โœ… 3. Nested Lookup

{{ data.student.name }}

๐Ÿ‘‰ Step-by-step:

  • data โ†’ dictionary
  • student โ†’ inner dictionary
  • name โ†’ value

๐Ÿง  Lookup Order (Important Theory Question)

When Django sees:

{{ obj.key }}

It checks in order:

  1. Dictionary key
  2. Object attribute
  3. List index

โš ๏ธ Common Errors


โŒ Using brackets

โŒ Wrong:

{{ marks[0] }}

โœ… Correct:

{{ marks.0 }}

โŒ Wrong key

๐Ÿ‘‰ Must match dictionary:

student = {"course": "MCA"}

โŒ Missing variable

๐Ÿ‘‰ Ensure passed in context:

return render(..., {'name': name})

๐Ÿงช Practice Questions

  1. Access third element of list
  2. Create nested dictionary and display values
  3. Display all marks in table
  4. Combine dictionary + list

๐ŸŽค Viva Questions & Answers


1. What is context in Django?

Context is a dictionary used to pass multiple variables from view to template.


2. How many variables can be passed in context?

Any number of variables can be passed. There is no strict limit.


3. How does Django perform variable lookup?

It checks dictionary keys first, then object attributes, and finally list indices.


4. How to access list elements in template?

Using dot notation like marks.0, marks.1.


5. Can we use brackets in templates?

No, Django templates do not support bracket notation like Python.


6. What is nested lookup?

Accessing values inside nested structures like dictionary inside dictionary.


7. What happens if key is not found?

Django displays empty output instead of error.


8. Why is lookup order important?

It helps understand how Django resolves variables and avoids confusion.


9. Can we pass objects also?

Yes, model objects can also be passed and accessed similarly.


10. What is dynamic rendering?

Displaying data dynamically based on context variables.


๐Ÿ”— Navigation

๐Ÿ‘‰ Next Post: Using {% include %} for Header and Footer
๐Ÿ‘‰ Back to List: Django Programs (60 Questions with Solutions)


Further Reading

Introduction to Django Framework and its Features

Django Practice Exercise

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

Inserting Information from Multiple CheckBox Selection in a Database Table in PHP

programmingempire

princites.com

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *