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

πŸ“Œ 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.py for form fields
  • views.py for logic
  • template for 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
  • FloatField allows 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 fields
  • floatformat:2 formats 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

  1. User opens form page
  2. Enters 5 marks
  3. Form is submitted using POST
  4. Django validates fields
  5. View calculates total and average
  6. 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

  1. Add pass/fail status based on average
  2. Display highest and lowest marks also
  3. Use 6 subjects instead of 5
  4. 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

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 *