Creating a Simple Calculator Using Django

Faraz

By Faraz -

Learn how to create a simple calculator using Django with this step-by-step tutorial. Perfect for beginners looking to enhance their web development skills.


creating-a-simple-calculator-using-django.webp

Introduction

Django is a powerful, high-level web framework for building robust web applications quickly and with less code. It's designed to help developers create complex, database-driven websites effortlessly.

Creating a calculator with Django is a great way to understand the fundamentals of this framework. It allows you to explore setting up views, templates, forms, and URL routing, which are essential components of any Django project.

In this article, we will walk through the process of creating a simple calculator using Django. By the end, you'll have a functional web-based calculator and a better grasp of how Django works.

Setting Up the Django Environment

1. Installing Django

To get started, you need to install Django using pip. Open your terminal and run:

pip install django

2. Creating a Django Project

Once Django is installed, create a new project by running:

django-admin startproject calculator_project

Navigate into your project directory:

cd calculator_project

3. Setting Up a Django App

Next, create a new app within your project:

python manage.py startapp calculator

Add the App to Your Project

Open calculator_project/settings.py and add 'calculator' to the INSTALLED_APPS list:

INSTALLED_APPS = [
    'calculator',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Understanding Django Project Structure

Project vs. App

A Django project is a collection of settings for an instance of Django, including database configuration, Django-specific options, and application-specific settings. An app, on the other hand, is a web application that does something—for example, a blog system, a database of public records, or a simple calculator.

Key Files and Directories

  • manage.py: A command-line utility for interacting with your project.
  • settings.py: Configuration for your project.
  • urls.py: URL declarations for your project.
  • views.py: Logic for processing user requests and returning responses.

Creating the Calculator App

Designing the App Structure

For our calculator, we'll need a basic structure:

  • views.py: To handle the logic of the calculator.
  • urls.py: To route requests to the appropriate view.
  • templates/: To hold the HTML files.

Creating Views for the Calculator

In calculator/views.py, add the following code:

from django.shortcuts import render

def calculator_view(request):
    return render(request, 'calculator.html')

Setting Up URL Routing

Configuring URLs for the Project

In calculator_project/urls.py, include the calculator app's URLs:

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

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

Adding URLs for the Calculator App

Create calculator/urls.py and add the following:

from django.urls import path
from .views import calculator_view

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

Creating the Calculator Template

Django templates are a way to generate HTML dynamically. We'll create a simple template for our calculator.

Create a Template Directory:

Inside the calculator directory, create a templates folder and an calculator.html file:

mkdir -p calculator/templates
touch calculator/templates/calculator.html

Design the Calculator Template:

In calculator/templates/calculator.html, add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator using Django</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
            font-family: Arial, sans-serif;
        }
        .calculator {
            border: 2px solid #333;
            border-radius: 10px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
            background-color: #fff;
            width: 320px;
        }
        .calculator-screen {
            background-color: #222;
            color: #fff;
            font-size: 2em;
            padding: 15px;
            text-align: right;
            border-bottom: 2px solid #333;
        }
        .calculator-buttons {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 1px;
        }
        .button {
            background-color: #eee;
            border: 1px solid #ccc;
            font-size: 1.5em;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .button:hover {
            background-color: #ddd;
        }
        .button.operator {
            background-color: #f9a825;
            color: #fff;
        }
        .button.operator:hover {
            background-color: #f57f17;
        }
        .button.double {
            grid-column: span 2;
        }
        .button.triple {
            grid-column: span 3;
        }
        .button.triple:hover {
            background-color: #f57f17;
        }
        .calculator-screen {
            border-radius: 10px 10px 0 0;
        }
        .bottom-left-radius{
            border-bottom-left-radius: 10px;
        }
        .bottom-right-radius{
            border-bottom-right-radius: 10px;
        }
    </style>
</head>
<body>
    <div class="calculator">
        <div class="calculator-screen">
            {{ result|default:"0" }}
        </div>
        <div class="calculator-buttons">
            <div class="button triple" id="ac">AC</div>
            <div class="button operator" id="divide">/</div>
            <div class="button" id="7">7</div>
            <div class="button" id="8">8</div>
            <div class="button" id="9">9</div>
            <div class="button operator" id="multiply">*</div>
            <div class="button" id="4">4</div>
            <div class="button" id="5">5</div>
            <div class="button" id="6">6</div>
            <div class="button operator" id="subtract">-</div>
            <div class="button" id="1">1</div>
            <div class="button" id="2">2</div>
            <div class="button" id="3">3</div>
            <div class="button operator" id="add">+</div>
            <div class="button double bottom-left-radius" id="0">0</div>
            <div class="button" id="decimal">.</div>
            <div class="button operator bottom-right-radius" id="equals">=</div>
        </div>
    </div>
    <script>
        const screen = document.querySelector('.calculator-screen');
        let currentInput = '';
        let operator = '';
        let firstOperand = '';
        document.querySelectorAll('.button').forEach(button => {
            button.addEventListener('click', () => {
                const value = button.id;
                if (value === 'ac') {
                    currentInput = '';
                    operator = '';
                    firstOperand = '';
                    screen.textContent = '0';
                } else if (value === 'equals') {
                    if (operator && firstOperand !== '') {
                        try {
                            currentInput = eval(`${firstOperand} ${operator} ${currentInput}`);
                            screen.textContent = currentInput;
                            operator = '';
                            firstOperand = '';
                        } catch {
                            screen.textContent = 'Error';
                        }
                    }
                } else if (['add', 'subtract', 'multiply', 'divide'].includes(value)) {
                    if (firstOperand === '') {
                        firstOperand = currentInput;
                    } else if (operator) {
                        firstOperand = eval(`${firstOperand} ${operator} ${currentInput}`);
                    }
                    operator = value === 'add' ? '+' : value === 'subtract' ? '-' : value === 'multiply' ? '*' : '/';
                    currentInput = '';
                } else {
                    if (value === 'decimal' && currentInput.includes('.')) {
                        return;
                    }
                    currentInput += value === 'decimal' ? '.' : value;
                    screen.textContent = currentInput;
                }
            });
        });
    </script>
</body>
</html>

Run the Server

Apply Migrations:

Apply migrations to set up the database (necessary even if not using a database for this app):

python manage.py migrate

Run the Development Server:

Start the Django development server:

python manage.py runserver

Visit Your App:

Open a web browser and navigate to http://127.0.0.1:8000/ to see your calculator app in action.

Deploying the Django Application

Preparing the App for Deployment

Update your settings for production:

  • Set DEBUG = False
  • Add your allowed hosts
  • Configure static file handling

Choosing a Hosting Service

Services like Heroku, AWS, and DigitalOcean are popular choices for deploying Django applications. Follow their documentation to deploy your app.

Conclusion

Congratulations on completing the tutorial on creating a simple calculator using Django! You now have a functional calculator app that you can use as a foundation for more complex projects. This tutorial has not only helped you understand the basics of Django but also provided you with practical experience in web development. Keep experimenting and building more applications to further enhance your skills.

FAQs

Q1. How do I install Django?

Install Django using pip:

pip install django

Q2. What are Django templates?

Django templates are a way to generate HTML dynamically, allowing you to separate design from business logic.

Q3. How can I style my Django application?

You can style your Django application using CSS, Bootstrap, or other front-end frameworks.

Q4. What are some good practices for Django development?

  • Use virtual environments.
  • Follow the Django project layout conventions.
  • Write tests for your code.

Q5. Where can I deploy my Django application?

Popular choices for deploying Django applications include Heroku, AWS, and DigitalOcean.

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺