๐ Introduction
In many academic applications, we need to:
- accept subject marks
- calculate total
- calculate average
In this program, we will create a Django form that accepts five marks from the user and displays:
- Total Marks
- Average Marks
๐ฏ Program Statement
๐ Create a form to input five marks and display total and average.
๐ง Concept
This program uses:
forms.pyfor form fieldsviews.pyfor logictemplatefor form and output display
โ๏ธ Step 1: Create Form
๐ File: forms.py
๐น Path:
myproject/myapp/forms.py
๐น Code:
from django import forms
class MarksForm(forms.Form):
mark1 = forms.FloatField(label='Enter Marks 1')
mark2 = forms.FloatField(label='Enter Marks 2')
mark3 = forms.FloatField(label='Enter Marks 3')
mark4 = forms.FloatField(label='Enter Marks 4')
mark5 = forms.FloatField(label='Enter Marks 5')
๐ง Explanation
- We created 5 fields for 5 subject marks
FloatFieldallows both whole numbers and decimal values
โ๏ธ Step 2: Create View
๐ File: views.py
๐น Path:
myproject/myapp/views.py
๐น Code:
from django.shortcuts import render
from .forms import MarksForm
def marks_total_average(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
})
๐ง Explanation
- Form values are collected using
cleaned_data - Total is calculated by adding all 5 marks
- Average is calculated by dividing total by 5
โ๏ธ Step 3: 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('marks-form/', views.marks_total_average, name='marks_form'),
]
โ๏ธ Step 4: Create Template
๐ File: marks_form.html
๐น Path:
myproject/templates/marks_form.html
๐น Code:
<!DOCTYPE html>
<html>
<head>
<title>Marks Form</title>
</head>
<body>
<h1>Marks Total and Average</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Calculate</button>
</form>
<hr>
{% if total is not None %}
<h2>Total Marks: {{ total }}</h2>
<h2>Average Marks: {{ average|floatformat:2 }}</h2>
{% endif %}
</body>
</html>
๐ง Explanation
{{ form.as_p }}displays all form fieldsfloatformat:2formats average to 2 decimal places- Output appears only after submission
โ๏ธ Step 5: Run Server
python manage.py runserver
๐ Step 6: Output
Open:
๐ http://127.0.0.1:8000/marks-form/
โ Example Input:
- Marks 1 = 80
- Marks 2 = 75
- Marks 3 = 90
- Marks 4 = 85
- Marks 5 = 70
โ Output:
Total Marks: 400
Average Marks: 80.00
๐ง How It Works
- User opens form page
- Enters 5 marks
- Form is submitted using POST
- Django validates fields
- View calculates total and average
- Template displays result
๐ฅ Key Concepts
Django Form
class MarksForm(forms.Form):
Defines the input structure.
POST Method
<form method="post">
Used to send form data securely.
Cleaned Data
form.cleaned_data['mark1']
Used to get validated input.
Average Calculation
average = total / 5
Divides total by number of subjects.
โ ๏ธ Common Errors
โ Forgot {% csrf_token %}
POST form will fail with security error.
โ Used CharField instead of FloatField
Marks should be numeric, so FloatField is better.
โ Result always visible
Use:
{% if total is not None %}
โ Wrong import in views.py
Use:
from .forms import MarksForm
โ Invalid input like text
Django form validation will automatically show error.
๐งช Practice Questions
- Add pass/fail status based on average
- Display highest and lowest marks also
- Use 6 subjects instead of 5
- Display grade according to average
๐ค Viva Questions & Answers
1. Why do we use forms.py in this program?
forms.py is used to define form fields in a structured way. It makes form creation, validation, and reuse easier.
2. Why is FloatField used for marks?
FloatField accepts numeric values including decimals. It is useful when marks may not always be whole numbers.
3. What is the purpose of cleaned_data?
cleaned_data contains validated and sanitized user input. It should be used after is_valid().
4. Why do we use POST method here?
POST method is used to send form data securely to the server. It is preferred for data submission.
5. Why is is_valid() necessary?
It checks whether the entered values are valid before performing calculations. Without it, invalid input may cause errors.
6. What is floatformat:2 in the template?
It is a Django template filter used to show the average up to 2 decimal places.
๐ Next Post: Create a Form to Input Three Numbers and Display the Largest Value
๐ 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
