Django Template and Form Programs with Solutions

This post provides solutions to a set of important Django practical questions based on template rendering, loops, filters, URL parameters, template inheritance, static files, and form handling. These programs are useful for lab work, practical exams, assignments, and viva preparation. At the end, there is a set of 40 viva questions for discussion and self-practice.


Contents

  1. Display the sum and product of two fixed numbers using template rendering
  2. Display attendance report with conditional status inside a loop
  3. Display a list of subjects using {% for %} loop in a template
  4. Demonstrate template filters such as upper, lower, length, and date
  5. Given a list of marks, display total, average, highest, lowest, and pass count
  6. Accept a number as URL parameter and display its square
  7. Implement template inheritance using {% extends %} and {% block %}
  8. Pass dictionary and list context data to a template and display values
  9. Use {% url %} and {% static %} template tags for navigation and static resources
  10. Create a form to input five marks and display total and average

1) Display the Sum and Product of Two Fixed Numbers Using Template Rendering

Objective

Create a Django view that sends two fixed numbers to a template. The template should display the numbers, their sum, and their product.

views.py

from django.shortcuts import render

def sum_product(request):
a = 10
b = 5
context = {
'a': a,
'b': b,
'sum': a + b,
'product': a * b
}
return render(request, 'sum_product.html', context)

urls.py

from django.urls import path
from . import views

urlpatterns = [
path('sum-product/', views.sum_product, name='sum_product'),
]

templates/sum_product.html

<!DOCTYPE html>
<html>
<head>
<title>Sum and Product</title>
</head>
<body>
<h2>Sum and Product of Two Fixed Numbers</h2>
<p>First Number: {{ a }}</p>
<p>Second Number: {{ b }}</p>
<p>Sum: {{ sum }}</p>
<p>Product: {{ product }}</p>
</body>
</html>

Output

If a = 10 and b = 5, the output will be:

  • Sum = 15
  • Product = 50

2) Display Attendance Report with Conditional Status Inside a Loop

Objective

Display attendance data of students using a loop. Show Present if attendance is 75 or above, otherwise show Short Attendance.

views.py

from django.shortcuts import render

def attendance_report(request):
students = [
{'name': 'Amit', 'attendance': 82},
{'name': 'Riya', 'attendance': 68},
{'name': 'Karan', 'attendance': 91},
{'name': 'Neha', 'attendance': 72},
]
return render(request, 'attendance_report.html', {'students': students})

urls.py

path('attendance-report/', views.attendance_report, name='attendance_report'),

templates/attendance_report.html

<!DOCTYPE html>
<html>
<head>
<title>Attendance Report</title>
</head>
<body>
<h2>Attendance Report</h2>
<table border="1" cellpadding="8">
<tr>
<th>Name</th>
<th>Attendance %</th>
<th>Status</th>
</tr>

{% for student in students %}
<tr>
<td>{{ student.name }}</td>
<td>{{ student.attendance }}</td>
<td>
{% if student.attendance >= 75 %}
Present
{% else %}
Short Attendance
{% endif %}
</td>
</tr>
{% endfor %}
</table>
</body>
</html>

3) Display a List of Subjects Using {% for %} Loop in a Template

Objective

Send a list of subjects from the view to the template and display them using the for loop.

views.py

from django.shortcuts import render

def subject_list(request):
subjects = ['Python', 'Django', 'DBMS', 'Operating System', 'Computer Networks']
return render(request, 'subject_list.html', {'subjects': subjects})

urls.py

path('subjects/', views.subject_list, name='subject_list'),

templates/subject_list.html

<!DOCTYPE html>
<html>
<head>
<title>Subject List</title>
</head>
<body>
<h2>List of Subjects</h2>
<ul>
{% for subject in subjects %}
<li>{{ subject }}</li>
{% endfor %}
</ul>
</body>
</html>

4) Demonstrate Template Filters Such as upper, lower, length, and date

Objective

Use Django template filters to format text, count list items, and display dates.

views.py

from django.shortcuts import render
from datetime import datetime

def template_filters_demo(request):
    name = "Juhi"
    city = "NEW DELHI"
    subjects = ['Python', 'Django', 'HTML', 'CSS']
    today = datetime.now()

    context = {
        'name': name,
        'city': city,
        'subjects': subjects,
        'today': today,
    }
    return render(request, 'filters_demo.html', context)

urls.py

path('filters-demo/', views.template_filters_demo, name='filters_demo'),

templates/filters_demo.html

<!DOCTYPE html>
<html>
<head>
<title>Template Filters Demo</title>
</head>
<body>
<h2>Template Filters Demo</h2>

<p>Original Name: {{ name }}</p>
<p>Uppercase Name: {{ name|upper }}</p>

<p>Original City: {{ city }}</p>
<p>Lowercase City: {{ city|lower }}</p>

<p>Total Subjects: {{ subjects|length }}</p>

<p>Current Date: {{ today|date:"d-m-Y" }}</p>
</body>
</html>

Explanation

  • upper converts text to uppercase
  • lower converts text to lowercase
  • length returns total number of items
  • date formats the date

5) Given a List of Marks, Display Total, Average, Highest, Lowest, and Pass Count

Objective

Use a Python list in the view and calculate required statistics before displaying them in the template.

views.py

from django.shortcuts import render

def marks_analysis(request):
marks = [67, 89, 45, 90, 76, 38, 55]

total = sum(marks)
average = total / len(marks)
highest = max(marks)
lowest = min(marks)
pass_count = len([m for m in marks if m >= 40])

context = {
'marks': marks,
'total': total,
'average': average,
'highest': highest,
'lowest': lowest,
'pass_count': pass_count
}

return render(request, 'marks_analysis.html', context)

urls.py

path('marks-analysis/', views.marks_analysis, name='marks_analysis'),

templates/marks_analysis.html

<!DOCTYPE html>
<html>
<head>
<title>Marks Analysis</title>
</head>
<body>
<h2>Marks Analysis</h2>

<p>Marks: {{ marks }}</p>
<p>Total: {{ total }}</p>
<p>Average: {{ average }}</p>
<p>Highest: {{ highest }}</p>
<p>Lowest: {{ lowest }}</p>
<p>Pass Count: {{ pass_count }}</p>
</body>
</html>

6) Accept a Number as URL Parameter and Display Its Square

Objective

Take a number directly from the URL and calculate its square.

views.py

from django.shortcuts import render

def number_square(request, num):
return render(request, 'square.html', {
'number': num,
'square': num * num
})

urls.py

path('square/<int:num>/', views.number_square, name='number_square'),

templates/square.html

<!DOCTYPE html>
<html>
<head>
<title>Square of Number</title>
</head>
<body>
<h2>Square Calculator</h2>
<p>Number: {{ number }}</p>
<p>Square: {{ square }}</p>
</body>
</html>

Example

If the URL is:

/square/8/

The output will be:

  • Number: 8
  • Square: 64

7) Implement Template Inheritance Using {% extends %} and {% block %}

Objective

Use a base template and inherit it in child templates.

templates/base.html

<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
<h1>Welcome to My Django Website</h1>
<hr>
{% block content %}
{% endblock %}
<hr>
<p>Footer Section</p>
</body>
</html>

templates/home.html

{% extends 'base.html' %}

{% block title %}Home Page{% endblock %}

{% block content %}
<h2>This is Home Page</h2>
<p>Template inheritance is working successfully.</p>
{% endblock %}

views.py

from django.shortcuts import render

def home(request):
return render(request, 'home.html')

urls.py

path('home/', views.home, name='home'),

Explanation

  • extends is used to inherit a parent template
  • block defines replaceable sections
  • This helps reuse common layout across multiple pages

8) Pass Dictionary and List Context Data to a Template and Display Values

Objective

Pass both dictionary and list from view to template.

views.py

from django.shortcuts import render

def context_demo(request):
student = {
'name': 'Anjali',
'course': 'MCA',
'city': 'Delhi'
}

hobbies = ['Reading', 'Coding', 'Music', 'Travel']

context = {
'student': student,
'hobbies': hobbies
}

return render(request, 'context_demo.html', context)

urls.py

path('context-demo/', views.context_demo, name='context_demo'),

templates/context_demo.html

<!DOCTYPE html>
<html>
<head>
<title>Context Demo</title>
</head>
<body>
<h2>Dictionary and List Context Demo</h2>

<h3>Student Details</h3>
<p>Name: {{ student.name }}</p>
<p>Course: {{ student.course }}</p>
<p>City: {{ student.city }}</p>

<h3>Hobbies</h3>
<ul>
{% for hobby in hobbies %}
<li>{{ hobby }}</li>
{% endfor %}
</ul>
</body>
</html>

9) Use {% url %} and {% static %} Template Tags for Navigation and Static Resources

Objective

Use Django template tags for dynamic links and loading CSS or images.

Step 1: Configure static files

settings.py

STATIC_URL = '/static/'

Project structure

app_name/
static/
css/
style.css
images/
logo.png

static/css/style.css

body {
font-family: Arial;
background-color: #f2f2f2;
}
h2 {
color: darkblue;
}

views.py

from django.shortcuts import render

def about(request):
return render(request, 'about.html')

def contact(request):
return render(request, 'contact.html')

urls.py

path('about/', views.about, name='about'),
path('contact/', views.contact, name='contact'),

templates/about.html

{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>About Page</title>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<img src="{% static 'images/logo.png' %}" alt="Logo" width="100">

<h2>About Us</h2>
<p>This page uses static files and dynamic navigation links.</p>

<a href="{% url 'contact' %}">Go to Contact Page</a>
</body>
</html>

templates/contact.html

{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Contact Page</title>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<h2>Contact Us</h2>
<p>This is the contact page.</p>

<a href="{% url 'about' %}">Go to About Page</a>
</body>
</html>

10) Create a Form to Input Five Marks and Display Total and Average

Objective

Accept five marks from the user using a Django form and display the total and average.

forms.py

from django import forms

class MarksForm(forms.Form):
mark1 = forms.IntegerField(label='Mark 1')
mark2 = forms.IntegerField(label='Mark 2')
mark3 = forms.IntegerField(label='Mark 3')
mark4 = forms.IntegerField(label='Mark 4')
mark5 = forms.IntegerField(label='Mark 5')

views.py

from django.shortcuts import render
from .forms import MarksForm

def marks_form(request):
total = None
average = None

if request.method == 'POST':
form = MarksForm(request.POST)
if form.is_valid():
m1 = form.cleaned_data['mark1']
m2 = form.cleaned_data['mark2']
m3 = form.cleaned_data['mark3']
m4 = form.cleaned_data['mark4']
m5 = form.cleaned_data['mark5']

total = m1 + m2 + m3 + m4 + m5
average = total / 5
else:
form = MarksForm()

return render(request, 'marks_form.html', {
'form': form,
'total': total,
'average': average
})

urls.py

path('marks-form/', views.marks_form, name='marks_form'),

templates/marks_form.html

<!DOCTYPE html>
<html>
<head>
<title>Marks Form</title>
</head>
<body>
<h2>Enter Five Marks</h2>

<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Calculate</button>
</form>

{% if total is not None %}
<h3>Result</h3>
<p>Total = {{ total }}</p>
<p>Average = {{ average }}</p>
{% endif %}
</body>
</html>

Complete urls.py Example

If you want to place all programs in one app, your urls.py may look like this:

from django.urls import path
from . import views

urlpatterns = [
path('sum-product/', views.sum_product, name='sum_product'),
path('attendance-report/', views.attendance_report, name='attendance_report'),
path('subjects/', views.subject_list, name='subject_list'),
path('filters-demo/', views.template_filters_demo, name='filters_demo'),
path('marks-analysis/', views.marks_analysis, name='marks_analysis'),
path('square/<int:num>/', views.number_square, name='number_square'),
path('home/', views.home, name='home'),
path('context-demo/', views.context_demo, name='context_demo'),
path('about/', views.about, name='about'),
path('contact/', views.contact, name='contact'),
path('marks-form/', views.marks_form, name='marks_form'),
]

Viva Questions


1. What is template rendering in Django?

Template rendering is the process of combining a template file with context data to generate dynamic HTML output. The render() function in Django is used to pass data from the view to the template. It helps separate business logic from presentation. This improves code maintainability and readability.


2. Why do we pass context data from views to templates?

Context data allows dynamic content to be displayed in templates instead of hardcoded values. It enables interaction between backend logic and frontend UI. For example, data from the database can be shown to users. Without context, templates would remain static.


3. What is the purpose of the render() function?

The render() function combines a template with context data and returns an HTTP response. It takes request, template name, and context dictionary as arguments. It simplifies template rendering compared to older methods. It is commonly used in all Django views.


4. What is the difference between a template and a static HTML page?

A static HTML page contains fixed content, while a Django template can display dynamic data. Templates use tags like {% %} and {{ }} for logic and variables. They interact with backend data. This makes web applications interactive and data-driven.


5. What is the purpose of the {% for %} loop in Django templates?

The {% for %} loop is used to iterate over lists or querysets in templates. It helps display multiple records such as students or subjects. It reduces repetition of HTML code. It is similar to loops in programming languages.


6. How do you access dictionary values inside a Django template?

Dictionary values are accessed using dot notation like {{ student.name }}. Django automatically maps keys to attributes. This makes templates cleaner and easier to read. It avoids complex syntax inside HTML.


7. What is the role of {% if %} in templates?

The {% if %} tag is used for conditional rendering of content. It allows displaying different outputs based on conditions. For example, attendance status can be shown as pass or fail. It improves logic handling in UI.


8. What are template filters in Django?

Template filters modify data before displaying it in templates. They are applied using the pipe symbol |. Examples include upper, lower, and length. They help format output without modifying backend code.


9. What does the upper filter do?

The upper filter converts text into uppercase letters. It is useful for formatting names or headings. It is applied using {{ name|upper }}. This avoids writing logic in views.


10. What is the use of the lower filter?

The lower filter converts text into lowercase. It ensures consistency in display. It is often used for emails or usernames. It improves readability and formatting.


11. What does the length filter return?

The length filter returns the number of elements in a list or characters in a string. It is useful for counting items dynamically. It helps avoid manual counting in views. Example: {{ list|length }}.


12. How is the date filter used in Django?

The date filter formats date objects into readable strings. It accepts format patterns like d-m-Y. It improves presentation of dates. Example: {{ today|date:"d-m-Y" }}.


13. Can arithmetic operations be done in templates?

Django templates have limited support for arithmetic operations. Complex calculations are discouraged in templates. Instead, calculations should be done in views. This maintains separation of concerns.


14. Why are calculations done in views instead of templates?

Views handle business logic while templates handle presentation. Performing calculations in views keeps templates clean. It also improves performance and maintainability. This follows MVC design principles.


15. What is a URL parameter in Django?

A URL parameter is a value passed through the URL to a view. It allows dynamic data processing. For example, /square/5/ passes 5 to the view. It enables dynamic routing.


16. What is the purpose of int:num in urls.py?

<int:num> captures an integer from the URL and passes it to the view. It ensures type validation. It simplifies parameter extraction. It is part of Django’s path converters.


17. How does Django connect URL to a view?

Django uses urls.py to map URLs to view functions. When a request is received, Django matches the URL pattern. The corresponding view is executed. This is called URL routing.


18. What is template inheritance?

Template inheritance allows reuse of common layout across multiple pages. A base template defines structure, and child templates extend it. It reduces duplication of code. It improves maintainability.


19. What is the role of {% extends %}?

{% extends %} is used to inherit a parent template. It allows child templates to reuse layout. Only specific sections are overridden. This makes design consistent.


20. What is the use of {% block %}?

{% block %} defines replaceable sections in templates. Child templates override these blocks. It provides flexibility in content customization. It is essential for template inheritance.


21. What is context in Django?

Context is a dictionary used to pass data from views to templates. It contains key-value pairs. Templates access this data using variables. It enables dynamic rendering.


22. What types of data can be sent in context?

Context can include strings, lists, dictionaries, querysets, and objects. It supports various data structures. This flexibility allows complex data representation. It is widely used in dynamic pages.


23. What is the purpose of {% url %} tag?

The {% url %} tag generates dynamic URLs based on view names. It avoids hardcoding URLs. It ensures maintainability when URLs change. It is used for navigation links.


24. Why is {% url %} better than hardcoding URLs?

Hardcoding URLs can break when paths change. {% url %} ensures links remain valid. It improves code maintainability. It also reduces errors.


25. What is the purpose of {% static %}?

{% static %} loads static resources like CSS, JS, and images. It generates correct file paths. It ensures proper resource linking. It is essential for frontend styling.


26. Why do we use {% load static %}?

{% load static %} enables static tag usage in templates. Without it, static files cannot be accessed. It is required at the top of templates. It activates static file handling.


27. What are static files in Django?

Static files include CSS, JavaScript, and images. They are not dynamically generated. They improve UI and user experience. Django manages them using STATIC settings.


28. What is a Django form?

A Django form is a Python class used to handle user input. It simplifies form creation and validation. It integrates with models and views. It ensures secure data handling.


29. What is the difference between HTML form and Django form?

HTML forms require manual validation, while Django forms provide built-in validation. Django forms are more secure and reusable. They reduce boilerplate code. They integrate easily with backend logic.


30. What is forms.py in Django?

forms.py is used to define form classes. It contains fields and validation rules. It separates form logic from views. It improves code organization.


31. What is form.as_p?

form.as_p renders form fields wrapped in paragraph tags. It simplifies HTML generation. It reduces manual coding. It is useful for quick form layouts.


32. Why is CSRF protection required?

CSRF protection prevents unauthorized form submissions. It protects against malicious attacks. Django provides built-in CSRF tokens. It ensures application security.


33. What is {% csrf_token %}?

{% csrf_token %} generates a hidden security token in forms. It validates requests. It prevents cross-site attacks. It must be included in POST forms.


34. What is the difference between GET and POST?

GET sends data via URL, while POST sends data in request body. GET is less secure. POST is used for sensitive operations. POST supports large data.


35. When should POST be used?

POST is used when submitting sensitive or large data. It is used for form submissions. It ensures data security. It prevents data exposure in URLs.


36. What is request.method?

request.method identifies the HTTP method used. It helps distinguish GET and POST requests. It controls form processing logic. It is used in views.


37. What is form.is_valid()?

form.is_valid() checks if form data passes validation rules. It ensures data correctness. It returns True or False. It must be called before accessing cleaned_data.


38. What is cleaned_data?

cleaned_data contains validated form data. It is safe to use. It removes invalid inputs. It is accessed after validation.


39. How do you calculate total and average in Django?

Values are taken from cleaned_data and processed in views. Total is calculated using sum. Average is derived by dividing total. Results are passed to templates.


40. What is the flow of a Django request?

User sends request → URL routing → View executes logic → Template renders → Response returned. This cycle defines Django workflow. It ensures structured processing.


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 *