Home / Blogs

How to Set Up a Currency Converter in Django?

Django
·

October 9, 2023

how-to-set-up-a-currency-converter-in-django

Welcome to our beginner-friendly guide to building a currency conversion app using Django! Have you ever wondered how to quickly convert amounts between different currencies?

In this blog, we’ll walk you through the step-by-step process of creating a user-friendly web app to calculate real-time currency conversions.

We’ll cover setting up your Django project, integrating a currency exchange API, creating a user-friendly interface, and handling potential errors. By the end of this guide, you’ll have a practical and interactive tool that makes currency conversion hassle-free. Let’s dive in and bring the world of currency conversion to your fingertips!

To read more about setting up a currency converter in Django, refer to our blog How to Set Up a Currency Converter in Django

Step 1: Setting up Your Django Project

Create a Django Project: If you don’t already have a Django project set up, you can create one using the following command in your terminal:

django-admin startproject currency_converter

Create a Django App: Create a new Django app inside your project directory. For the purpose of this tutorial, let’s call it conversion.

cd currency_converter
python manage.py startapp conversion

Configure Settings: Open the settings.py file of your project (currency_converter/settings.py) and add ‘conversion’ to the INSTALLED_APPS list.

Database Migration: Run the initial database migration to set up the necessary database tables for your app.

python manage.py makemigrations conversion
python manage.py migrate

URL Configuration: In the urls.py file of your conversion app (conversion/urls.py), define the URL patterns for your currency conversion views. You can start with a simple placeholder view for now.

from django.urls import path
from . import views

app_name = 'conversion'

urlpatterns = [
    path('convert/', views.convert_currency, name='convert_currency'),
    # Add more URL patterns as needed
]

Create Views: Create a new file called views.py in your conversion app directory (conversion/views.py). This is where you’ll define the logic for your currency conversion views.

from django.shortcuts import render

def convert_currency(request):
    # Your conversion logic will go here
    return render(request, 'conversion/convert_currency.html')

Create Templates: Create a directory named Templates inside your conversion app directory if it doesn’t already exist. Inside the templates directory, create another directory called conversion, and within that, create a file named convert_currency.html. This is where you’ll create the HTML template for your currency conversion page.

Your directory structure should look like this:

currency_converter/
├── conversion/
│   ├── templates/
│   │   ├── conversion/
│   │   │   ├── convert_currency.html

With this step completed, you’ve set up the basic structure of your Django project and app for currency conversion. The first step involved creating the project, setting up an app, configuring URLs, and creating a placeholder view along with an HTML template. In the next step, you can start working on the actual currency conversion logic and integrate third-party APIs if needed.

Step 2: Adding Currency Conversion Logic

In this step, we’ll start building the currency conversion logic within your Django app. We’ll use a simple form to take input from the user and then perform the conversion based on that input. We’ll also integrate a currency exchange rate API for real-time conversion rates.

Install Requests Library: We’ll use the requests library to make API requests. If you haven’t installed it yet, you can do so using the following command:

pip install requests

Update Views: Open the views.py file of your conversion app (conversion/views.py) and update the convert_currency view to handle form submissions and currency conversion logic.

import requests
from django.shortcuts import render

def convert_currency(request):
    if request.method == 'POST':
        amount = float(request.POST.get('amount'))
        from_currency = request.POST.get('from_currency')
        to_currency = request.POST.get('to_currency')

        # Replace 'YOUR_API_KEY' with your actual API key
        api_key = 'YOUR_API_KEY'
        endpoint = f'https://api.apilayer.com/exchangerates_data/latest?base={from_currency}&apikey={api_key}'

        response = requests.get(endpoint)
        data = response.json()
        conversion_rate = data['rates'][to_currency]

        converted_amount = amount * conversion_rate

        context = {
            'amount': amount,
            'from_currency': from_currency,
            'to_currency': to_currency,
            'conversion_rate': conversion_rate,
            'converted_amount': converted_amount,
        }
        return render(request, 'conversion/convert_currency.html', context)

    return render(request, 'conversion/convert_currency.html')

Create the Form: In the same views.py file, import Django’s Form and ChoiceField classes. Define a simple form class that will allow users to input the amount, source currency, and target currency.

from django import forms

class CurrencyConversionForm(forms.Form):
    amount = forms.FloatField(label='Amount')
    from_currency = forms.ChoiceField(choices=[('USD', 'USD'), ('EUR', 'EUR'), ('JPY', 'JPY')], label='From Currency')
    to_currency = forms.ChoiceField(choices=[('USD', 'USD'), ('EUR', 'EUR'), ('JPY', 'JPY')], label='To Currency')

Update the Template: Open the convert_currency.html template file you created earlier. Add the form to the template and display the conversion results.

<!DOCTYPE html>
<html>
<head>
    <title>Currency Conversion</title>
</head>
<body>
    <h1>Currency Conversion</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Convert</button>
    </form>
    {% if converted_amount %}
        <p>Conversion Rate: {{ conversion_rate }}</p>
        <p>Converted Amount: {{ converted_amount }}</p>
    {% endif %}
</body>
</html>

With this step completed, your Django app now includes the currency conversion logic. Users can enter an amount and select source and target currencies, and upon submission, the app will fetch the conversion rate using the provided API, perform the conversion, and display the results on the template. In the next step, you can work on enhancing the user interface and error handling for a more user-friendly experience.

Step 3: Enhancing User Interface and Error Handling

In this step, we’ll focus on improving the user interface of the currency conversion form and implementing error handling for potential issues.

Update Template:

Open the convert_currency.html template file in your conversion app’s templates directory. Add some additional styling to the form and display error messages if needed.

<!DOCTYPE html>
<html>
<head>
    <title>Currency Conversion</title>
</head>
<body>
    <h1>Currency Conversion</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.non_field_errors }}
        <div>
            <label for="{{ form.amount.id_for_label }}">Amount:</label>
            {{ form.amount }}
            {{ form.amount.errors }}
        </div>
        <div>
            <label for="{{ form.from_currency.id_for_label }}">From Currency:</label>
            {{ form.from_currency }}
            {{ form.from_currency.errors }}
        </div>
        <div>
            <label for="{{ form.to_currency.id_for_label }}">To Currency:</label>
            {{ form.to_currency }}
            {{ form.to_currency.errors }}
        </div>
        <button type="submit">Convert</button>
    </form>
    {% if converted_amount %}
        <p>Conversion Rate: {{ conversion_rate }}</p>
        <p>Converted Amount: {{ converted_amount }}</p>
    {% endif %}
</body>
</html>

Error Handling:

Update the convert_currency view in views.py to handle possible errors such as API request failures or invalid input. You can display error messages using the form’s built-in error handling mechanism.

def convert_currency(request):
    form = CurrencyConversionForm()

    if request.method == 'POST':
        form = CurrencyConversionForm(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']

            # API and conversion logic here

            context = {
                'form': form,
                'amount': amount,
                'from_currency': from_currency,
                'to_currency': to_currency,
                'conversion_rate': conversion_rate,
                'converted_amount': converted_amount,
            }
            return render(request, 'conversion/convert_currency.html', context)

    context = {'form': form}
    return render(request, 'conversion/convert_currency.html', context)

Styling:

You can apply CSS styles to your template to enhance the visual appearance of the form and results. You can either link an external stylesheet or include inline styles directly in the HTML.

API Error Handling:

It’s important to implement proper error handling for API requests. If the API request fails, you can catch the exception and display an appropriate error message to the user. You can also check if the API response contains the necessary data before proceeding with the conversion.

By completing this step, your currency conversion app will have an improved user interface with better error handling. Users will receive feedback for input errors and potential API issues, creating a more user-friendly experience.

To read more about implementing a captcha in Django, refer to our blog How to Implement Captcha in Django in 2023

Horilla Editorial Team Author

Horilla Editorial Team is a group of experienced writers and editors who are passionate about HR software. We have a deep understanding of the HR landscape and are committed to providing our readers with the most up-to-date and informative content. We have written extensively on a variety of HR software topics, including applicant tracking systems, performance management software, and payroll software etc. We are always looking for new ways to share our knowledge with the HR community. If you have a question about HR software, please don't hesitate to contact us.