Create a Currency Converter Using Django

Faraz

By Faraz - August 05, 2024

Learn how to build a currency converter using Django with this easy-to-follow guide. Perfect for beginners looking to enhance their Python and web development skills.


create-a-currency-converter-using-django.webp

Creating a currency converter using Django is a great way to improve your web development skills. Whether you're a beginner or someone looking to brush up on your Django knowledge, this guide will walk you through the process step by step. By the end of this tutorial, you'll have a fully functional currency converter that you can use as part of a larger project or just as a standalone tool.

Prerequisites

Before we dive in, make sure you have a basic understanding of Django and web development. You'll need the following tools and libraries installed on your machine:

  • Python (version 3.6 or higher)
  • Django (version 3.0 or higher)
  • A text editor or IDE (such as VS Code or PyCharm)
  • Basic knowledge of HTML and CSS

Setting Up the Development Environment

Installing Django

Before starting, ensure you have Python installed. You can install Django using pip:

pip install django

Creating a new Django project

Create a new Django project using the following command:

django-admin startproject currency_converter

Setting up the project structure

Navigate into your project directory:

cd currency_converter

Create a Django App

Create a new app within your project:

python manage.py startapp converter

Adding the app to the project

In currency_converter/settings.py, add converter to the INSTALLED_APPS list:

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

Creating the Currency Converter App

Create Forms

In converter, create a new file named forms.py and add the following function:

from django import forms

class ConversionForm(forms.Form):
    amount = forms.DecimalField(
        max_digits=10,
        decimal_places=2,
        label='Amount',
        widget=forms.NumberInput(attrs={'class': 'form-control'})
    )
    from_currency = forms.ChoiceField(
        choices=[
            ('USD', 'USD'),
            ('EUR', 'EUR'),
            ('GBP', 'GBP'),
            ('INR', 'INR'),
            ('SAR', 'SAR'),
            ('KWD', 'KWD')
            # Add more currencies as needed
        ],
        label='From Currency',
        widget=forms.Select(attrs={'class': 'form-control'})
    )
    to_currency = forms.ChoiceField(
        choices=[
            ('INR', 'INR'),
            ('USD', 'USD'),
            ('EUR', 'EUR'),
            ('GBP', 'GBP'),
            ('SAR', 'SAR'),
            ('KWD', 'KWD')
            # Add more currencies as needed
        ],
        label='To Currency',
        widget=forms.Select(attrs={'class': 'form-control'})
    )

Create Views

Next, we’ll create views. Open converter/views.py and add the following:

from django.shortcuts import render
from .forms import ConversionForm
from decimal import Decimal, ROUND_HALF_UP
import requests

def convert_currency(amount, from_currency, to_currency):
    url = f"https://api.exchangerate-api.com/v4/latest/{from_currency}"
    response = requests.get(url)
    data = response.json()
    rate = data['rates'].get(to_currency, 1)
    if isinstance(rate, float):
        rate = Decimal(rate)
    amount_decimal = Decimal(amount)
    converted_amount = amount_decimal * rate
    converted_amount = converted_amount.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)

    return converted_amount

def home(request):
    result = None
    if request.method == 'POST':
        form = ConversionForm(request.POST)
        if form.is_valid():
            amount = form.cleaned_data['amount']
            from_currency = form.cleaned_data['from_currency']
            to_currency = form.cleaned_data['to_currency']
            converted_amount = convert_currency(amount, from_currency, to_currency)
            result = f"{to_currency} {converted_amount}"
    else:
        form = ConversionForm()
    return render(request, 'home.html', {'form': form, 'result': result})

Set Up URL Routing

Add a URL pattern for your view. In converter/urls.py (create this file if it doesn't exist), add:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
]

Include the app's URLs in your project's URL configuration. Open currency_converter/urls.py and include the currency converter app URLs:

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

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

Create Templates

Create a templates directory within the currency converter app and then create home.html file inside this directory.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Currency Converter</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(to right, #00c6ff, #0072ff);
            font-family: 'Arial', sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        .container {
            max-width: 400px;
            width: 100%;
        }
        .converter-card {
            background: #ffffff;
            border-radius: 15px;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
            padding: 20px;
        }
        .converter-card-header {
            background: #0072ff;
            color: white;
            padding: 15px;
            border-radius: 15px 15px 0 0;
            text-align: center;
            font-size: 1.5em;
            font-weight: bold;
        }
        .card-body {
            padding: 20px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-control {
            border-radius: 10px;
        }
        .btn-primary {
            background: #0072ff;
            border: none;
            border-radius: 10px;
            padding: 10px 20px;
            transition: background 0.3s;
        }
        .btn-primary:hover {
            background: #0056b3;
        }
        .result {
            text-align: center;
        }
        .result h2 {
            font-size: 1.2em;
            color: #333;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="converter-card">
            <div class="converter-card-header">
                <i class="fas fa-exchange-alt"></i> Currency Converter
            </div>
            <div class="card-body">
                <form method="post">
                    {% csrf_token %}
                    <div class="form-group">
                        {{ form.amount.label_tag }}
                        {{ form.amount}}
                        {% for error in form.amount.errors %}
                            <div class="text-danger">{{ error }}</div>
                        {% endfor %}
                    </div>
                    <div class="form-group">
                        {{ form.from_currency.label_tag }}
                        {{ form.from_currency}}
                        {% for error in form.from_currency.errors %}
                            <div class="text-danger">{{ error }}</div>
                        {% endfor %}
                    </div>
                    <div class="form-group">
                        {{ form.to_currency.label_tag }}
                        {{ form.to_currency}}
                        {% for error in form.to_currency.errors %}
                            <div class="text-danger">{{ error }}</div>
                        {% endfor %}
                    </div>
                    <button type="submit" class="btn btn-primary w-100">Convert</button>
                </form>
            </div>
            {% if result %}
                <div class="result">
                    <h2>Converted Amount: {{ result }}</h2>
                </div>
            {% endif %}
        </div>
    </div>
</body>
</html>

Run Your Server

Run migrations:

python manage.py makemigrations
python manage.py migrate

Run the development server:

python manage.py runserver

Open your browser and go to http://127.0.0.1:8000 to see your currency converter app in action.

Full Currency Converter App Project Structure

currency_converter/
│
├── converter/         # Main app directory
│   ├── migrations/             # Database migrations
│   │   ├── __init__.py
│   │
│   ├── templates/              # HTML templates
│   │   └── home.html
│   │
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── forms.py                # Django forms
│   ├── models.py               # Models (if any)
│   ├── tests.py                # Unit tests
│   ├── urls.py                 # App-specific URLs
│   ├── views.py                # Views
│   └── utils.py                # Utility functions like currency conversion
│
├── currency_converter/ # Main project directory
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py             # Project settings
│   ├── urls.py                 # Project-level URLs
│   ├── wsgi.py
│
├── manage.py                   # Django management script
└── requirements.txt            # Dependencies (optional)

Conclusion

Building a currency converter with Django is a practical project that helps you understand the basics of web development, Python, and Django. It's not only a great way to learn, but also a useful tool that you can customize and expand upon. By following this guide, you now have a working currency converter and the skills to create even more complex web applications with Django.

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🥺