Django

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

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *