๐ 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
