[Answered ]-Pass an output of a function to django filter

2๐Ÿ‘

I replicated your classes and filter, and the following is working for me:

#template_additions.py
from django import template
register = template.Library()

@register.filter
def convert(value, conversion_rate):
    return float(value * conversion_rate)

#models.py
class Money(object):
    def __init__(self, amount):
        self.amount = amount

class ConversionRate(object):
    def __init__(self, euro_rate):
        self.euro_rate = euro_rate

    def euro_rate(self):
        return float(self.euro_rate)

#views.py
from django.shortcuts import render
from your_app.models import Money, ConversionRate

def test(request):
    money = Money(amount=100)
    conversion_rate = ConversionRate(euro_rate=0.90)
    return render(request, 'test.html', {'money' : money,
         'conversion_rate' : conversion_rate})

#test.html
{% load template_additions %}
{{ money.amount|convert:conversion_rate.euro_rate }}

outputs:
90

๐Ÿ‘คBrandon Taylor

Leave a comment