Create Age Calculator in Django - Step-by-Step Guide

Faraz

By Faraz - July 27, 2024

Learn how to create an age calculator in Django with this detailed tutorial. Follow our step-by-step guide to build a functional age calculator using Django.


create-age-calculator-in-django-step-by-step-guide.webp

Introduction

Creating web applications can be a fun and rewarding experience, especially when using a powerful framework like Django. In this guide, we'll walk through creating a simple yet functional age calculator using Django. This tutorial is perfect for beginners who want to get their hands dirty with Django and learn the basics of this popular Python web framework.

Setting Up the Django Environment

1. Installing Django

Before we dive into creating our age calculator, we need to install Django. You can do this by running the following command:

pip install django

This command installs Django and its dependencies.

2. Setting up a Django Project

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

django-admin startproject age_calculator

This command creates a new directory called age_calculator containing the initial project structure.

Navigate into your project directory:

cd age_calculator

3. Creating a Django App

Within our project, we'll create a new app called calculator:

python manage.py startapp calculator

This creates a new directory called calculator where we will write our application code.

Setting Up the Project Structure

Understanding Django Project Structure

Django projects are organized into a specific structure that includes the main project directory, settings, URLs, and apps. Here's a brief overview of the important files and directories:

  • age_calculator/: The project directory.
  • calculator/: The app directory.
  • settings.py: Configuration settings for the project.
  • urls.py: URL declarations for the project.
  • views.py: Functions that handle the logic for web requests.

Configuring Settings

Open age_calculator/settings.py and add the new app 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',
]

This tells Django to include our app in the project.

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 the Age Calculator Form

Create a form in calculator/forms.py:

from django import forms

class AgeCalculatorForm(forms.Form):
    date_of_birth = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}))

Creating the Age Calculator View

Open calculator/views.pyand create a view for our age calculator:

from django.shortcuts import render
from datetime import date
from .forms import AgeCalculatorForm

def calculate_age(birth_date):
    today = date.today()
    age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day))
    return age

def age_calculator_view(request):
    age = None
    if request.method == 'POST':
        form = AgeCalculatorForm(request.POST)
        if form.is_valid():
            birth_date = form.cleaned_data['date_of_birth']
            age = calculate_age(birth_date)
    else:
        form = AgeCalculatorForm()
    return render(request, 'age_calculator.html', {'form': form, 'age': age})

Setting Up URL Routing

Configuring URLs for the Project

Open age_calculator/urls.pyand include the 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 a new file called calculator/urls.py and add the following code:

from django.urls import path
from .views import age_calculator_view

urlpatterns = [
    path('', age_calculator_view, name='age_calculator'),
]

Creating the Age Calculator Template

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

Create a Template Directory:

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

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

Design the Calculator Template:

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

<!DOCTYPE html>
<html>
<head>
    <title>Age Calculator</title>
    <style>
        body {
    font-family: Arial, sans-serif;
    background-color: #f0f2f5;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
}
.container {
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    text-align: center;
    width: 300px;
}
h1 {
    font-size: 24px;
    margin-bottom: 20px;
}
form {
    display: flex;
    flex-direction: column;
}
input[type="date"] {
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
}
button {
    padding: 10px;
    border: none;
    border-radius: 4px;
    background-color: #007bff;
    color: #fff;
    font-size: 16px;
    cursor: pointer;
}
button:hover {
    background-color: #0056b3;
}
.age-result {
    margin-top: 20px;
    font-size: 18px;
    color: #333;
}
    </style>
</head>
<body>
    <div class="container">
        <h1>Age Calculator</h1>
        <form method="post">
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit">Calculate Age</button>
        </form>
        {% if age is not None %}
            <div class="age-result">
                <h2>Your age is: {{ age }}</h2>
            </div>
        {% endif %}
    </div>
</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 go to http://127.0.0.1:8000/ to test the age calculator.

Full Project Structure

age_calculator/
    age_calculator/
        __init__.py
        settings.py
        urls.py
        wsgi.py
    calculator/
        __init__.py
        admin.py
        apps.py
        forms.py
        migrations/
        models.py
        tests.py
        urls.py
        views.py
        templates/
                age_calculator.html
    manage.py

This basic Django project should give you a functional age calculator. You can expand on this by adding styles, error handling, and additional features as needed.

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

Deploying to a Live Server

You can deploy your Django application to a live server using various hosting services like Heroku, DigitalOcean, or AWS. Follow the deployment guides provided by these services to get your application online.

Conclusion

We hope this tutorial on creating an age calculator in Django has been helpful and informative. By following these steps, you have learned how to set up a Django project, handle user inputs, and perform age calculations based on a given birth date. This project not only reinforces your understanding of Django but also adds a useful feature to your web development toolkit. Keep exploring and experimenting with Django to build even more sophisticated applications in the future.

FAQs

Q1. How can I customize the age calculator?

You can customize the age calculator by adding more features such as calculating age in months and days, or by improving the user interface with CSS and JavaScript.

Q2. What are some advanced features I can add?

Advanced features include adding user authentication to save and track age calculations, integrating a database to store birth dates, or creating an API to allow other applications to use your age calculator.

Q3. How can I ensure the security of my Django application?

To ensure security, always validate and sanitize user input, use Django's built-in security features, keep your software up to date, and follow best practices for securing web applications.

Q4. Are there any limitations to the Django age calculator?

The main limitation is that it only calculates age based on the current date. For more complex calculations, such as accounting for time zones or historical date changes, additional logic would be needed.

Q5. Where can I find more Django resources?

You can find more Django resources on the official Django documentation, various online tutorials, and Django-focused books and courses.

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🥺