Django

Create a Form to Input Three Numbers and Display the Largest Value

πŸ“Œ 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.py for defining form fields
  • views.py for comparison logic
  • template for 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
  • FloatField is 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 None prevents 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

  1. User opens the form page
  2. Enters three numbers
  3. Form is submitted using POST method
  4. Django validates the input
  5. View finds the maximum value
  6. 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

  1. Display the smallest number instead of the largest
  2. Accept four numbers and display the largest
  3. Also display all entered numbers below the result
  4. Use manual if-elif-else logic instead of max()

🎀 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

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 *