3

Is there any facility in Django for doing currency conversions? Obviously, rates change day by day but I'm somewhat hopeful that the locale module has some sort of web-service based converter.

There's a snippet here that handles the formatting: http://www.djangosnippets.org/snippets/552/ But I need to localize the values first.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Koobz
  • 6,928
  • 6
  • 41
  • 53

4 Answers4

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
  • 430
  • 3
  • 7
  • Thanks, this works! I hackishly put this in my settings.py, storing the result as USD_TO_EUR (what I needed), and then the code can access this anywhere. With a cron to SIGHUP gunicorn daily (I already had this), this will get updated at least that often. – mrooney Sep 21 '12 at 19:27
1
# 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.

Stranger6667
  • 418
  • 3
  • 17
  • I tried this but I get an error MissingRate at /customer Rate EUR -> USD does not exist. I opened a question: https://stackoverflow.com/questions/66867845/how-to-solve-missingrate-error-in-django – edche Mar 30 '21 at 11:16
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..

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129