- Write your filter in app/templatetags/tags.py:
from decimal import Decimal
from django import template
register = template.Library()
@register.filter(name="convert_currency")
def convert_currency(value, rate):
"""
Converts the given amount to a different currency using the specified rate.
Usage: {{ value|convert_currency:rate }}
"""
try:
value = Decimal(value)
rate = Decimal(rate)
return round(value * rate, 2)
except (ValueError, TypeError, Decimal.InvalidOperation):
return value
- Use it in your template HTML. The "value" (here
amount
) gets piped into the filter (like in Unix), and any arguments (hererate
) are added after the colon:
{{ amount }} USD ({{ amount|convert_currency:rate }} AUD)
Note that it's recommended to use Decimal here, because:
# Using floats
total = 0.1 + 0.1 + 0.1
print(total) # Expected: 0.3, Actual: 0.30000000000000004
# Using Decimal
from decimal import Decimal
total = Decimal('0.1') + Decimal('0.1') + Decimal('0.1')
print(total) # Exactly 0.3
#django