DEV Community 👩‍💻👨‍💻

Cover image for Create a Custom Template Tag for Currency Conversion in Django
paulsaul621
paulsaul621

Posted on

Create a Custom Template Tag for Currency Conversion in Django

Introduction.

In Django, template tags and filters are pieces of code that can be used in Django templates to perform various tasks. Template tags and filters can be used to display data in a certain format, perform mathematical calculations, or even to create custom functionality. In this blog, we will explore how to create custom template tags and filters in Django.

Getting Started.

Inside your Django app directory, create a module called templatetags and add an empty init.py file as shown in the below directory structure.

my_app/
├── __init__.py
├── admin.py
├── models.py
├── templatetags/
│   ├── __init__.py
│   └── currency_converter.py
└── views.py
Enter fullscreen mode Exit fullscreen mode

Next, open the currency_converter.py file and add these two lines to get started with custom template tags and filters.

from django import template
register = template.Library()
Enter fullscreen mode Exit fullscreen mode

Make currency_converter available by loading it in templates.

{% load currency_converter %}
Enter fullscreen mode Exit fullscreen mode

Creating our Custom Template Filter.

Django comes with a lot of built-in template tags and filters which you can use right away.
If you want to write custom template filters, you can either use assignment tags or write custom filters.

Assignment Tags

Assignment tags return a value that can be assigned to a variable in the template. For example, the following assignment tag will return the current date and time:

@register.assignment_tag
def get_current_time():
    return datetime.datetime.now()
Enter fullscreen mode Exit fullscreen mode

You can then use it in your template like this:

{% get_current_time %}
Enter fullscreen mode Exit fullscreen mode

Custom Filters

Custom filters are used to modify variables in the template. For example, the following filter will convert a string to uppercase:

@register.filter
def upper(value):
    return value.upper()
Enter fullscreen mode Exit fullscreen mode

You can then use it in your template like this:

{{ value|upper }}
Enter fullscreen mode Exit fullscreen mode

In our case, we want to create a template filter that does currency conversion on our template. Create a simple view in views.py, that renders a string as follows:

def my_view(request):
    context = {
        "amount": "200",
    }
    return render(request, "index.html", context)
Enter fullscreen mode Exit fullscreen mode

After creating views, create a simple template filter named currency in currency_converter.py

from django import template
import requests

register = template.Library()

def currency(value, arg):
    convertedValue = requests.get('https://pesapedia.co.ke/musk/exchangerate?from=KES&to='+arg+'&amount='+str(value))
    convertedValue = convertedValue.json()
    convertedValue = convertedValue['result']
    return convertedValue


register.filter('currency', currency)    
Enter fullscreen mode Exit fullscreen mode

Here's what the above function is doing:

  1. It first makes a get request to the API
  2. Once it gets the response, it converts it to a json object
  3. The data received is a dictionary with key "result". We access the value of "result"
  4. We then return the value of "result"

So basically, we're returning the converted value of some currency to another

The URL above used for currency conversion is free to use, i developed it as a result of not finding any reliable free currency conversion api. It returns the response below:

{
    "credits": {
        "message": "Feel free to follow me on LinkedIn",
        "url": "https://www.linkedin.com/in/paul-wababu-660b511a7/"
    },
    "success": true,
    "query": {
        "from": "KES",
        "to": "USD",
        "amount": 200
    },
    "info": {
        "rate": 1.650773
    },
    "historical": false,
    "date": "2022-10-24",
    "result": 1.650773
}
Enter fullscreen mode Exit fullscreen mode

You can now use the currency filter in your templates like so:

{% load custom_tags %}

{{ amount | currency:"USD"}}<br>

Enter fullscreen mode Exit fullscreen mode

In the code above, the amount is converted to USD from KSH. Feel free to modify this to suit your needs.

Conclusion

That's it! You've now created a custom template tag for currency conversion in Django. This is a powerful tool that can be used to easily display prices in different currencies on your website or application.
I hope this tutorial was helpful in showing you how to create a custom template tag for currency conversion in Django. If you have any questions or comments, please feel free to leave them below.

Top comments (0)

DEV

Thank you.

 
Thanks for visiting DEV, we’ve worked really hard to cultivate this great community and would love to have you join us. If you’d like to create an account, you can sign up here.