How to Build a Calculator App in Python Django

One of the most common beginner projects that helps bridge the gap between learning Python and building real web apps is creating a calculator. But instead of a basic console app, why not build a web-based calculator using Django? It’s practical, interactive, and a great way to sharpen your Django skills.

In this guide, I will walk you through creating a calculator app in Django from scratch. You’ll learn how to set up the project, create views, handle user input, and display results dynamically on a web page. By the end, you’ll have a fully functional calculator app that can perform basic arithmetic operations, addition, subtraction, multiplication, and division.

Let’s get started!

Build a Calculator App in Django

When I first started with Django, building a calculator app was a great way to understand how Django handles user input, processes data, and renders HTML templates dynamically. Unlike desktop calculators, a Django web app is accessible from any device with a browser, making it versatile.

Also, this project introduces you to core Django concepts, URL routing, views, templates, and forms, in a simple, digestible way.

Read Create a Search Autocomplete with a Filter in Django

Set Up Your Django Project

Before diving into code, ensure you have Python and Django installed. You can install Django via pip if you haven’t already:

pip install django

Next, create a new Django project and app:

django-admin startproject calculator_project
cd calculator_project
python manage.py startapp calculator

Add the calculator app to your project’s settings.py under INSTALLED_APPS:

INSTALLED_APPS = [
    ...
    'calculator',
]

Check out Register User with OTP Verification in Django

Create the Calculator View

The heart of our app is the view that processes the user’s input and performs calculations.

Open calculator/views.py and add the following code:

from django.shortcuts import render

def calculator_view(request):
    result = None
    error = None

    if request.method == 'POST':
        try:
            num1 = float(request.POST.get('num1'))
            num2 = float(request.POST.get('num2'))
            operation = request.POST.get('operation')

            if operation == 'add':
                result = num1 + num2
            elif operation == 'subtract':
                result = num1 - num2
            elif operation == 'multiply':
                result = num1 * num2
            elif operation == 'divide':
                if num2 == 0:
                    error = "Cannot divide by zero."
                else:
                    result = num1 / num2
            else:
                error = "Invalid operation selected."
        except (ValueError, TypeError):
            error = "Please enter valid numbers."

    return render(request, 'calculator/calculator.html', {'result': result, 'error': error})

Explanation:

  • The view checks if the request method is POST, meaning the user submitted the form.
  • It extracts the two numbers and the operation from the form data.
  • Depending on the operation, it performs the calculation or returns an error if the input is invalid (e.g., division by zero).
  • The result or error message is passed to the template for display.

Define URL Patterns

Next, link the view to a URL. In calculator/urls.py create this file if it doesn’t exist, and add:

from django.urls import path
from .views import calculator_view

urlpatterns = [
    path('', calculator_view, name='calculator'),
]

Now, include these URLs in the main project urls.py (calculator_project/urls.py):

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('calculator/', include('calculator.urls')),
]

Read Python Django Convert Date Time to String

Create the HTML Template

Create a folder named templates inside the calculator app directory, then inside it create another folder named calculator. Finally, create a file named calculator.html:

calculator/templates/calculator/calculator.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Simple Calculator App</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 40px auto;
            max-width: 400px;
            padding: 20px;
            background-color: #f5f5f5;
            border-radius: 8px;
            box-shadow: 0 0 10px #ccc;
        }
        input[type="number"], select {
            width: 100%;
            padding: 8px;
            margin: 8px 0 16px 0;
            box-sizing: border-box;
        }
        button {
            width: 100%;
            padding: 10px;
            background-color: #007bff;
            border: none;
            color: white;
            font-size: 16px;
            cursor: pointer;
            border-radius: 4px;
        }
        button:hover {
            background-color: #0056b3;
        }
        .result, .error {
            margin-top: 20px;
            font-weight: bold;
            font-size: 18px;
        }
        .error {
            color: red;
        }
    </style>
</head>
<body>
    <h2>Simple Calculator</h2>
    <form method="post">
        {% csrf_token %}
        <label for="num1">First Number:</label>
        <input type="number" step="any" id="num1" name="num1" required>

        <label for="num2">Second Number:</label>
        <input type="number" step="any" id="num2" name="num2" required>

        <label for="operation">Operation:</label>
        <select id="operation" name="operation" required>
            <option value="add">Add (+)</option>
            <option value="subtract">Subtract (-)</option>
            <option value="multiply">Multiply (×)</option>
            <option value="divide">Divide (÷)</option>
        </select>

        <button type="submit">Calculate</button>
    </form>

    {% if result is not None %}
        <div class="result">Result: {{ result }}</div>
    {% endif %}

    {% if error %}
        <div class="error">{{ error }}</div>
    {% endif %}
</body>
</html>

Check out Python Django Import Functions

Run Your Calculator App

Make sure you’re in the root directory of your Django project (calculator_project), then run:

python manage.py runserver

Open your browser and navigate to:
http://127.0.0.1:8000/calculator/

You should see your calculator app ready to perform arithmetic operations.

You can refer to the screenshot below to see the output.

django calculator app

Read Django User Registration with Email Confirmation

Alternative Method: Use Django Forms

If you want to handle user input more cleanly, Django’s forms module can help with validation and rendering. Here’s a quick overview:

  1. Create a form class in calculator/forms.py:
from django import forms

class CalculatorForm(forms.Form):
    num1 = forms.FloatField(label='First Number')
    num2 = forms.FloatField(label='Second Number')
    OPERATION_CHOICES = [
        ('add', 'Add (+)'),
        ('subtract', 'Subtract (-)'),
        ('multiply', 'Multiply (×)'),
        ('divide', 'Divide (÷)'),
    ]
    operation = forms.ChoiceField(choices=OPERATION_CHOICES)
  1. Modify the view to use this form:
from django.shortcuts import render
from .forms import CalculatorForm

def calculator_view(request):
    result = None
    error = None
    if request.method == 'POST':
        form = CalculatorForm(request.POST)
        if form.is_valid():
            num1 = form.cleaned_data['num1']
            num2 = form.cleaned_data['num2']
            operation = form.cleaned_data['operation']

            try:
                if operation == 'add':
                    result = num1 + num2
                elif operation == 'subtract':
                    result = num1 - num2
                elif operation == 'multiply':
                    result = num1 * num2
                elif operation == 'divide':
                    if num2 == 0:
                        error = "Cannot divide by zero."
                    else:
                        result = num1 / num2
            except Exception as e:
                error = str(e)
        else:
            error = "Invalid input. Please check your entries."
    else:
        form = CalculatorForm()

    return render(request, 'calculator/calculator_form.html', {'form': form, 'result': result, 'error': error})
  1. Create the template calculator/templates/calculator/calculator_form.html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Calculator with Django Forms</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 40px auto;
            max-width: 400px;
            padding: 20px;
            background-color: #f9f9f9;
            border-radius: 8px;
            box-shadow: 0 0 10px #ddd;
        }
        label, select, input {
            display: block;
            width: 100%;
            margin-bottom: 10px;
            padding: 8px;
            box-sizing: border-box;
        }
        button {
            width: 100%;
            padding: 10px;
            background-color: #28a745;
            border: none;
            color: white;
            font-size: 16px;
            cursor: pointer;
            border-radius: 5px;
        }
        button:hover {
            background-color: #218838;
        }
        .result, .error {
            margin-top: 20px;
            font-weight: bold;
            font-size: 18px;
        }
        .error {
            color: red;
        }
    </style>
</head>
<body>
    <h2>Calculator Using Django Forms</h2>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Calculate</button>
    </form>

    {% if result is not None %}
        <div class="result">Result: {{ result }}</div>
    {% endif %}

    {% if error %}
        <div class="error">{{ error }}</div>
    {% endif %}
</body>
</html>

This method leverages Django’s built-in form validation and renders the form fields automatically, making your code cleaner and easier to maintain.

Building this calculator app was a great reminder of how Django’s core components come together to create interactive web applications. Whether you choose the direct POST handling method or Django forms, you’ll get hands-on experience with views, templates, URL routing, and form handling.

This project is a perfect starting point if you want to build more complex web apps like budgeting tools, unit converters, or even small business calculators tailored for the US market.

Keep experimenting and happy coding!

You can find more Django tutorials and projects on PythonGuides.com to continue leveling up your skills. If you want to explore how to run Python scripts inside Django or create CRUD apps with Bootstrap, those are excellent next steps.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.