Pass Dictionary and List Context Data to Template and Display Values

πŸ“Œ Introduction

In Django, data is passed from view β†’ template using a context dictionary.

πŸ‘‰ Types of data we can pass:

  • Variables
  • Lists
  • Dictionaries

This program demonstrates:

  • Passing a list
  • Passing a dictionary
  • Displaying both in template

🎯 Program Statement

πŸ‘‰ Pass dictionary and list context data to a template and display values.


βš™οΈ Step 1: Create View


πŸ“ File: views.py

πŸ”Ή Path:

myproject/myapp/views.py

πŸ”Ή Code:

from django.shortcuts import render

def student_data(request):

    # List data
    subjects = ["Python", "Java", "Django", "AI"]

    # Dictionary data
    student = {
        "name": "Cherry",
        "age": 18,
        "course": "BCA"
    }

    return render(request, 'student.html', {
        'subjects': subjects,
        'student': student
    })

🧠 Explanation

  • subjects β†’ list
  • student β†’ dictionary
  • Both passed using context

βš™οΈ 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('student/', views.student_data),
]

βš™οΈ Step 3: Create Template


πŸ“ File: student.html

πŸ”Ή Path:

myproject/templates/student.html

πŸ”Ή Code:

<!DOCTYPE html>
<html>
<head>
<title>Student Data</title>
</head>
<body>

<h1>Student Details</h1>

<!-- Dictionary Access -->
<p>Name: {{ student.name }}</p>
<p>Age: {{ student.age }}</p>
<p>Course: {{ student.course }}</p>

<hr>

<h2>Subjects List</h2>

<!-- List Access -->
<ul>
{% for sub in subjects %}
<li>{{ sub }}</li>
{% endfor %}
</ul>

</body>
</html>

βš™οΈ Step 4: Run Server

python manage.py runserver

🌐 Step 5: Output

πŸ‘‰ http://127.0.0.1:8000/student/


βœ… Output:

Student Details

Name: Cherry
Age: 18
Course: BCA

Subjects List:
β€’ Python
β€’ Java
β€’ Django
β€’ AI

🧠 How It Works

  1. View creates list and dictionary
  2. Passes them via context
  3. Template accesses:
    • Dictionary β†’ student.name
    • List β†’ loop using {% for %}
  4. Data displayed

🧠 Syntax Summary


βœ… Passing Data:

return render(request, 'file.html', {'key': value})

βœ… Access Dictionary:

{{ student.name }}

βœ… Loop List:

{% for item in list %}
{{ item }}
{% endfor %}

⚠️ Common Errors


❌ Key mismatch

πŸ‘‰ Must match:

'student': student
{{ student.name }}

❌ Loop not working

πŸ‘‰ Check:

{% for sub in subjects %}

❌ Dictionary not displaying

πŸ‘‰ Use dot notation:

{{ student.name }}

NOT:

{{ student['name'] }}

πŸ§ͺ Practice Questions

  1. Pass list of 5 students
  2. Pass dictionary of employee
  3. Display list in table format
  4. Add nested dictionary

🎀 Viva Questions & Answers


1. What is context in Django?

Context is a dictionary used to pass data from view to template. It contains key-value pairs.


2. How do we pass data to template?

Using render(request, template, context). Context contains variables to display.


3. How do we access dictionary in template?

Using dot notation like {{ student.name }}. It is simple and readable.


4. How do we display list data?

Using {% for %} loop to iterate and display each item.


5. Can we pass multiple data types?

Yes, we can pass lists, dictionaries, strings, numbers, and objects.


6. What is key-value pair in context?

Key is variable name used in template. Value is actual data from view.


7. Why not use student['name']?

Django templates use dot notation for simplicity and security.


8. What is dynamic data rendering?

Displaying data that comes from backend instead of static HTML.


9. What happens if key is wrong?

Template will not display data and may show empty output.


10. Can we pass database data similarly?

Yes, QuerySets can also be passed like lists and displayed in templates.


πŸ”— Navigation

πŸ‘‰ Next Post: Multiple Context and Variable Lookup
πŸ‘‰ 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

Leave a Reply

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