Django

Fetch Model Data and Display it Dynamically in Templates

๐Ÿ“Œ Introduction

After inserting records into the database, the next step is to retrieve (fetch) data and display it on a web page.

In Django:

  • Data is fetched in views.py
  • Passed to template as context
  • Displayed using template variables

๐ŸŽฏ Program Statement

๐Ÿ‘‰ Fetch model data and display it dynamically in templates.


๐Ÿง  Prerequisite

We use the same Student model from previous posts.

๐Ÿ“ File: models.py

๐Ÿ”น Path:

myproject/myapp/models.py
from django.db import models

class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
course = models.CharField(max_length=100)
email = models.EmailField(unique=True)

def __str__(self):
return self.name

โš™๏ธ Step 1: Create View to Fetch Data


๐Ÿ“ File: views.py

๐Ÿ”น Path:

myproject/myapp/views.py

๐Ÿ”น Code:

from django.shortcuts import render
from .models import Student

def student_list(request):
students = Student.objects.all() # Fetch all records

return render(request, 'student_list.html', {
'students': students
})

๐Ÿง  Explanation

  • Student.objects.all() fetches all records from database
  • Data is stored in variable students
  • Passed to template as 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('students/', views.student_list, name='student_list'),
]

โš™๏ธ Step 3: Create Template


๐Ÿ“ File: student_list.html

๐Ÿ”น Path:

myproject/templates/student_list.html

๐Ÿ”น Code:

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

<h1>Student Records</h1>

{% if students %}
{% for s in students %}
<p>
Name: {{ s.name }} |
Age: {{ s.age }} |
Course: {{ s.course }} |
Email: {{ s.email }}
</p>
{% endfor %}
{% else %}
<p>No records found.</p>
{% endif %}

</body>
</html>

๐Ÿง  Explanation

  • {% for %} loop is used to iterate over records
  • {{ s.name }} accesses model field values
  • {% if students %} checks if data exists

โš™๏ธ Step 4: Run Server

python manage.py runserver

๐ŸŒ Step 5: Output

๐Ÿ‘‰ Open:

http://127.0.0.1:8000/students/


โœ… Example Output:

Student Records

Name: Cherry | Age: 20 | Course: MCA | Email: cherry@example.com  
Name: Aman   | Age: 22 | Course: BCA | Email: aman@example.com  
Name: Riya   | Age: 21 | Course: MCA | Email: riya@example.com  

๐Ÿง  How It Works

  1. View fetches data using ORM
  2. Data stored in variable students
  3. Passed to template via context
  4. Template loops through data
  5. Data displayed dynamically

๐Ÿ”ฅ Key Concepts


Fetch All Records

Student.objects.all()

Returns all rows from table.


Passing Context

return render(request, 'template.html', {'students': students})

Sends data to template.


Template Loop

{% for s in students %}

Used to iterate over data.


Access Fields

{{ s.name }}

Accesses model attributes.


Conditional Display

{% if students %}

Checks if data exists.


โš ๏ธ Common Errors


โŒ Forgot to import model

from .models import Student

โŒ Wrong template name

Ensure:

'student_list.html'

matches actual file name.


โŒ Using wrong variable name

If you pass:

{'students': students}

then template must use:

{% for s in students %}

โŒ No records in database

Then output will show:

No records found.

โŒ Template not found error

Ensure:

  • templates folder exists
  • added in settings.py

๐Ÿงช Practice Questions

  1. Display only names of students
  2. Filter students with age > 22
  3. Show total number of students
  4. Display records in table format
  5. Order students by name

๐ŸŽค Viva Questions & Answers


1. How do we fetch data from a model in Django?

We use the Django ORM, for example Student.objects.all() to fetch all records.


2. What is QuerySet in Django?

A QuerySet is a collection of objects retrieved from the database.


3. What is the role of view in data fetching?

The view fetches data from the model and sends it to the template.


4. What is context in Django?

Context is a dictionary used to pass data from view to template.


5. How do we display data in template?

Using template variables like {{ variable }} and loops.


6. What is {% for %} loop used for?

It is used to iterate over a list or QuerySet.


7. What happens if no data is present?

We can handle it using {% if %} condition and display a message.


8. Can we filter data before sending to template?

Yes, using ORM methods like filter(), exclude(), etc.


9. Why is this called dynamic content?

Because data is fetched from database at runtime and displayed.


๐Ÿ‘‰ Next Post: Display Model Records in Table Format using a List View
๐Ÿ‘‰ 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 *