๐ 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
- View fetches data using ORM
- Data stored in variable
students - Passed to template via context
- Template loops through data
- 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:
templatesfolder exists- added in
settings.py
๐งช Practice Questions
- Display only names of students
- Filter students with age > 22
- Show total number of students
- Display records in table format
- 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
Examples of Array Functions in PHP
Registration Form Using PDO in PHP
Inserting Information from Multiple CheckBox Selection in a Database Table in PHP
- Angular
- ASP.NET
- C
- C#
- C++
- CSS
- Dot Net Framework
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- PHP
- Power Bi
- Python
- Scratch 3.0
- TypeScript
- VB.NET
