Django

Display Model Records in Table Format using a List View

πŸ“Œ Introduction

In real applications, data is usually displayed in a tabular format rather than plain text.

In this program, we will:

  • fetch student records from database
  • display them in a structured HTML table
  • use Django template loops

🎯 Program Statement

πŸ‘‰ Display model records in table format using a list view.


🧠 Prerequisite

We use the same Student model from previous posts.


βš™οΈ Step 1: Create View


πŸ“ File: views.py

πŸ”Ή Path:

myproject/myapp/views.py

πŸ”Ή Code:

from django.shortcuts import render
from .models import Student

def student_table(request):
students = Student.objects.all()

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

🧠 Explanation

  • Fetch all records using ORM
  • Pass data to template as students

βš™οΈ 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-table/', views.student_table, name='student_table'),
]

βš™οΈ Step 3: Create Template (Table Format)


πŸ“ File: student_table.html

πŸ”Ή Path:

myproject/templates/student_table.html

πŸ”Ή Code:

<!DOCTYPE html>
<html>
<head>
<title>Student Table</title>
<style>
table {
border-collapse: collapse;
width: 80%;
margin: auto;
}
th, td {
border: 1px solid black;
padding: 10px;
text-align: center;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>

<h1 style="text-align:center;">Student Table</h1>

{% if students %}
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Course</th>
<th>Email</th>
</tr>

{% for s in students %}
<tr>
<td>{{ s.id }}</td>
<td>{{ s.name }}</td>
<td>{{ s.age }}</td>
<td>{{ s.course }}</td>
<td>{{ s.email }}</td>
</tr>
{% endfor %}
</table>
{% else %}
<p style="text-align:center;">No records found.</p>
{% endif %}

</body>
</html>

🧠 Explanation

  • <table> is used for structured display
  • {% for %} loop creates rows dynamically
  • {{ s.id }} shows auto-generated primary key
  • Styling improves readability

βš™οΈ Step 4: Run Server

python manage.py runserver

🌐 Step 5: Output

πŸ‘‰ Open:

http://127.0.0.1:8000/student-table/


βœ… Example Output:

IDNameAgeCourseEmail
1Kanchan20MCAkanchan@example.com
2Aman22BCAaman@example.com
3Riya21MCAriya@example.com

🧠 How It Works

  1. View fetches all records
  2. Data passed to template
  3. Template creates table structure
  4. Loop fills table rows dynamically

πŸ”₯ Key Concepts


Fetch Data

Student.objects.all()

Table Structure

<table>

Used for tabular data display.


Loop for Rows

{% for s in students %}

Creates one row per record.


Access Fields

{{ s.name }}

Displays model field value.


Primary Key

{{ s.id }}

Auto-generated ID field.


⚠️ Common Errors


❌ Table not displaying

Check:

{% if students %}

❌ Missing loop

If you forget:

{% for s in students %}

no rows will be displayed.


❌ CSS not applied

Ensure <style> block is correctly written.


❌ Wrong variable name

If context uses:

{'students': students}

template must use:

students

❌ No data in database

Then output will show:

No records found.

πŸ§ͺ Practice Questions

  1. Add serial number column
  2. Add alternating row colors
  3. Sort students by name
  4. Add β€œView Details” link in each row
  5. Add total record count below table

🎀 Viva Questions & Answers


1. Why do we use table format for displaying data?

Table format organizes data in rows and columns, making it easier to read and understand.


2. What is the role of {% for %} loop in table?

It is used to generate table rows dynamically for each record.


3. What is {{ s.id }}?

It is the primary key automatically created by Django for each record.


4. What is the difference between Post 45 and Post 46?

Post 45 displays data in plain text, while Post 46 displays data in a structured table format.


5. What happens if no records exist?

The {% if %} condition displays a message like β€œNo records found.”


6. Why is styling added in table?

Styling improves readability and presentation of data.


7. Can we use Bootstrap instead of CSS?

Yes, Bootstrap can be used for better design and responsiveness.


8. Where is data fetched from?

Data is fetched from the database using Django ORM.


9. What is a list view?

A list view displays multiple records of a model.


10. Why is this program important?

Displaying data in tables is a very common requirement in real-world applications and exams.


πŸ‘‰ Next Post: Create a Detail Page to Display Information of a Single Record
πŸ‘‰ 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 *