开发者

Pass an output of a function to django filter

I have a scenario in which I have to pass the output of a function to Django custom filter. Consider the object:

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

class ConversionRate(object):

   def GetEuroRate(self):
      ... some calculation and return a float value.


   def GetGBPRate(self):
      ... some calculation and return a float value.


    ..... more functions.

I have passed money and conversion rate instances as a context variable. I am trying to pass the different conversion rate. In this example, 'money' and 'conversion_rate' are context variables to refer to Money object and ConversionRate object respectively.

 {{ money|convert:conversion_rate.GetEuroRate }}

My filter code:

@register.filter
d开发者_JS百科ef convert(first_value, second_value):
   """Returns the product to two numbers."""
    return float(first_value * float(second_value)

In my custom filter, the conversion_rate.GetEuroRate() always returns 0 and not the actual value. Is there a way to pass the output of the function?

Thanks,

Kartik


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜