Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 8903

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T05:27:07+00:00 2024-11-28T05:27:07+00:00

Create a Custom Template Tag for Currency Conversion in Django

  • 60k

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.

apidjangopythonwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.