[Django]-Django Currency Conversion

5👍

Probably more elegant ways to do this, but it works.

currency_in = 'USD'
currency_out = 'NOK'
import urllib2
req = urllib2.urlopen('http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='+currency_in+currency_out+'=X')
result = req.read()
# result = "USDNOK=X",5.9423,"5/3/2010","12:39pm"

Then you can split() the result for the modifier.

👤twined

2👍

# Install google-currency package

# pip install google-currency

>>> from google_currency import convert  

>>> convert('usd', 'bdt', 1) 

Output:

{"from": "USD", "to": "BDT", "amount": "85.30", "converted": true}

0👍

You could use django-money app for currency conversions in Django-based projects.

It works with different rate sources and provides an interface to perform conversions & money localization:

>>> # After app setup & adding rates to the DB
>>> from djmoney.money import Money
>>> from djmoney.contrib.exchange.models import convert_money
>>> value = Money(100, 'EUR')
>>> converted = convert_money(value, 'USD')
>>> converted
<Money: 122.8184375038380800 USD>
>>> str(converted)
US$122.82

Formats are easily customizable, you could find the documentation on the project page.

0👍

You can use django-money to handle money values including the conversion of currencies as shown below. *The example below converts 100 USD to ... EUR and if using celery beat, you can automatically update the exchange rates of currencies:

# "views.py"

from django.http import HttpResponse
from app.models import MyModel
from djmoney.contrib.exchange.models import convert_money
from djmoney.money import Money

def test(request):
    print(convert_money(Money(100, 'USD'), 'EUR')) # Here
    return HttpResponse("Test")

You can see my answer and django-money doc which explain more about how to convert currencies and how to automatically update the exchange rates of currencies with celery beat..

Leave a comment