Django

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

You may also like...

Leave a Reply

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