This snippet is a combination of the existing currency snippets I found and some modifications to use your own settings without the need to have the locale installed on the system.
You can define in settings.py:
DECIMAL_SEPARATOR = ','
THOUSAND_SEPARATOR = '.'
CURRENCY_SYMBOL = u'€'
With the above settings, using {{ 1234.30|currency }}
on a template would result in €1.234,30
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | from django import template
from django.conf import settings
register = template.Library()
@register.filter()
def currency(value):
symbol = '$'
thousand_sep = ''
decimal_sep = ''
# try to use settings if set
try:
symbol = settings.CURRENCY_SYMBOL
except AttributeError:
pass
try:
thousand_sep = settings.THOUSAND_SEPARATOR
decimal_sep = settings.DECIMAL_SEPARATOR
except AttributeError:
thousand_sep = ','
decimal_sep = '.'
intstr = str(int(value))
f = lambda x, n, acc=[]: f(x[:-n], n, [(x[-n:])]+acc) if x else acc
intpart = thousand_sep.join(f(intstr, 3))
return "%s%s%s%s" % (symbol, intpart, decimal_sep, ("%0.2f" % value)[-2:])
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
In Your code even if settings.DECIMAL_SEPARATOR exist it won't be set until settings.THOUSAND_SEPARATOR exist too - it's wrong.
Correct & simplistic code:
Also You should mark
currency
filter asis_safe
, because someone may provide currency symbol as numeric reference, like: "€".regards.
#
Thanks.
#
Please login first before commenting.