Create a POST Form to Add Two Numbers and Display the Result

πŸ“Œ Introduction

In this program, we will:

  • Take two numbers from user
  • Use a POST form
  • Calculate sum
  • Display result on same page

πŸ‘‰ This is one of the most important beginner programs in Django forms


🎯 Program Statement

πŸ‘‰ Create a POST form to add two numbers and display the result.


🧠 Concept

This program uses:

  • forms.py β†’ input fields
  • views.py β†’ logic (addition)
  • template β†’ display form + result

βš™οΈ Step 1: Create Form Class


πŸ“ File: forms.py

πŸ”Ή Path:

myproject/myapp/forms.py

πŸ”Ή Code:

from django import forms

class AddForm(forms.Form):
num1 = forms.FloatField(label='Enter First Number')
num2 = forms.FloatField(label='Enter Second Number')

🧠 Explanation

  • FloatField allows decimal numbers
  • Two inputs: num1 and num2

βš™οΈ Step 2: Create View


πŸ“ File: views.py

πŸ”Ή Path:

myproject/myapp/views.py

πŸ”Ή Code:

from django.shortcuts import render
from .forms import AddForm

def add_numbers(request):
result = None

if request.method == 'POST':
form = AddForm(request.POST)
if form.is_valid():
n1 = form.cleaned_data['num1']
n2 = form.cleaned_data['num2']
result = n1 + n2
else:
form = AddForm()

return render(request, 'add.html', {
'form': form,
'result': result
})

🧠 Explanation

  • Get numbers using cleaned_data
  • Add numbers
  • Store result
  • Send to template

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

βš™οΈ Step 4: Create Template


πŸ“ File: add.html

πŸ”Ή Path:

myproject/templates/add.html

πŸ”Ή Code:

<!DOCTYPE html>
<html>
<head>
<title>Add Numbers</title>
</head>
<body>

<h1>Add Two Numbers</h1>

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

<hr>

{% if result is not None %}
<h2>Result: {{ result }}</h2>
{% endif %}

</body>
</html>

🧠 Explanation

  • method="post" β†’ sends data securely
  • {% csrf_token %} β†’ mandatory
  • Result shown only after submission

βš™οΈ Step 5: Run Server

python manage.py runserver

🌐 Step 6: Output

πŸ‘‰ http://127.0.0.1:8000/add/


βœ… Example Input:

  • Number 1: 10
  • Number 2: 20

βœ… Output:

Result: 30

🧠 How It Works

  1. User enters numbers
  2. Form submits via POST
  3. Django validates data
  4. View calculates sum
  5. Result sent to template
  6. Template displays result

πŸ”₯ Key Concepts


POST Method

<form method="post">

Used for sending data securely.


FloatField

forms.FloatField()

Accepts decimal numbers.


Cleaned Data

form.cleaned_data['num1']

Gives validated input.


Conditional Display

{% if result %}

Shows result only after submission.


⚠️ Common Errors


❌ Forgot CSRF token

πŸ‘‰ Error: CSRF verification failed


❌ Using request.POST directly

πŸ‘‰ Always use:

form.cleaned_data

❌ Wrong field type

πŸ‘‰ Use FloatField instead of CharField


❌ Result always showing

πŸ‘‰ Fix using:

{% if result is not None %}

πŸ§ͺ Practice Questions

  1. Perform subtraction instead of addition
  2. Add multiplication
  3. Add division with zero check
  4. Display result in colored text

🎀 Viva Questions & Answers


1. What is POST method?

POST method is used to send data securely from client to server. It does not display data in URL.


2. Why use FloatField in this program?

FloatField allows decimal numbers, making it more flexible than IntegerField.


3. What is cleaned_data?

It contains validated and cleaned input values after form validation.


4. Why use is_valid()?

To ensure that the data entered by user is correct before processing.


5. What is CSRF token?

It is a security feature to protect against cross-site request forgery attacks.


6. Can we perform operations in template?

No, logic should be written in views, not in templates.


7. Why is result initially None?

To prevent result from displaying before form submission.


8. What happens if user enters text instead of number?

Form validation will fail and error will be shown.


9. Can we use GET instead of POST?

Yes, but POST is preferred for form submissions.


10. Why is this program important?

It demonstrates complete form handling cycle: input β†’ validation β†’ processing β†’ output.


πŸ‘‰ Next Post: BMI Calculator using POST Form
πŸ‘‰ 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 *