π Introduction
In many programming problems, we need to compare numbers and find the maximum value.
In this program, we will:
- create a Django form
- accept three numbers from the user
- compare them
- display the largest number
This program is useful for understanding:
- Django forms
- POST method
- conditional logic in views
π― Program Statement
π Create a form to input three numbers and display the largest value.
π§ Concept
This program uses:
forms.pyfor defining form fieldsviews.pyfor comparison logictemplatefor displaying the form and result
βοΈ Step 1: Create Form
π File: forms.py
πΉ Path:
myproject/myapp/forms.py
πΉ Code:
from django import forms
class LargestNumberForm(forms.Form):
num1 = forms.FloatField(label='Enter First Number')
num2 = forms.FloatField(label='Enter Second Number')
num3 = forms.FloatField(label='Enter Third Number')
π§ Explanation
- We created three input fields
FloatFieldis used so the form can accept both integers and decimal values
βοΈ Step 2: Create View
π File: views.py
πΉ Path:
myproject/myapp/views.py
πΉ Code:
from django.shortcuts import render
from .forms import LargestNumberForm
def largest_number(request):
result = None
if request.method == 'POST':
form = LargestNumberForm(request.POST)
if form.is_valid():
n1 = form.cleaned_data['num1']
n2 = form.cleaned_data['num2']
n3 = form.cleaned_data['num3']
result = max(n1, n2, n3)
else:
form = LargestNumberForm()
return render(request, 'largest_number.html', {
'form': form,
'result': result
})
π§ Explanation
- Form values are collected using
cleaned_data - Pythonβs
max()function is used to find the largest value - The result is then passed to the 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('largest/', views.largest_number, name='largest_number'),
]
βοΈ Step 4: Create Template
π File: largest_number.html
πΉ Path:
myproject/templates/largest_number.html
πΉ Code:
<!DOCTYPE html>
<html>
<head>
<title>Largest Number</title>
</head>
<body>
<h1>Find the Largest Number</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Find Largest</button>
</form>
<hr>
{% if result is not None %}
<h2>Largest Number: {{ result }}</h2>
{% endif %}
</body>
</html>
π§ Explanation
{{ form.as_p }}displays the form fields neatly- The result is shown only after form submission
result is not Noneprevents blank or premature output
βοΈ Step 5: Run Server
python manage.py runserver
π Step 6: Output
Open:
π http://127.0.0.1:8000/largest/
β Example Input:
- First Number = 15
- Second Number = 42
- Third Number = 27
β Output:
Largest Number: 42
π§ How It Works
- User opens the form page
- Enters three numbers
- Form is submitted using POST method
- Django validates the input
- View finds the maximum value
- Template displays the largest number
π₯ Key Concepts
Django Form
class LargestNumberForm(forms.Form):
Defines the structure of the input form.
POST Method
<form method="post">
Used to send input data to the server.
Validation
if form.is_valid():
Checks whether entered values are valid numbers.
Maximum Value
result = max(n1, n2, n3)
Finds the largest among three numbers.
β οΈ Common Errors
β Forgot {% csrf_token %}
Django will show a CSRF verification error for POST forms.
β Using CharField instead of FloatField
This may accept text input and make comparisons harder.
β Result not showing
Use:
{% if result is not None %}
instead of only {% if result %}.
β Form import error
In views.py, import the form correctly:
from .forms import LargestNumberForm
β Invalid input like text
Django form validation will automatically show an error message.
π§ͺ Practice Questions
- Display the smallest number instead of the largest
- Accept four numbers and display the largest
- Also display all entered numbers below the result
- Use manual
if-elif-elselogic instead ofmax()
π€ Viva Questions & Answers
1. Why do we use FloatField here?
FloatField is used because it allows both integer and decimal input values. This makes the form more flexible.
2. What is the role of forms.py in this program?
forms.py defines the structure of the form, including the fields and their types. It also helps with validation.
3. Why is POST method used here?
POST method is used because the user is submitting data to the server for processing. It is safer than GET for form submission.
4. What does is_valid() do?
is_valid() checks whether the submitted input satisfies all validation rules. Only after this should we process the data.
5. What is cleaned_data?
cleaned_data contains validated user input in a clean form. It is the recommended way to access submitted values.
6. Why is max() used in the view?
max() is a built-in Python function that returns the largest value among the given inputs. It simplifies the comparison logic.
7. Can we find the largest number using if-else instead of max()?
Yes, we can use conditional statements like if, elif, and else to compare the numbers manually. Both methods are valid.
8. Why should comparison logic be written in the view?
The view handles the program logic, while the template is only for presentation. This separation keeps the code clean and maintainable.
π Next Post: Create a Temperature Converter Form (Celsius to Fahrenheit)
π 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
