Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 24, 2022 04:56 am GMT

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

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

from django import templateregister = template.Library()

Make currency_converter available by loading it in templates.

{% load currency_converter %}

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_tagdef get_current_time():    return datetime.datetime.now()

You can then use it in your template like this:

{% get_current_time %}

Custom Filters

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

@register.filterdef upper(value):    return value.upper()

You can then use it in your template like this:

{{ value|upper }}

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)

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

from django import templateimport requestsregister = 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 convertedValueregister.filter('currency', currency)    

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}

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

{% load custom_tags %}{{ amount | currency:"USD"}}<br>

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.


Original Link: https://dev.to/paulwababu/create-a-custom-template-tag-for-currency-conversion-in-django-7ok

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To