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 fieldsviews.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
FloatFieldallows decimal numbers- Two inputs:
num1andnum2
βοΈ 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
- User enters numbers
- Form submits via POST
- Django validates data
- View calculates sum
- Result sent to template
- 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
- Perform subtraction instead of addition
- Add multiplication
- Add division with zero check
- 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
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
