Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Params to Django Model Methods

In a Django model passing a param to a method and using it in the code is easy.

Class Foo(models.Model):
    number = IntegerField()
    ...
    def bar(self, percent):
        return self.number * percent

f = Foo(number=250)
f.bar(10)

The question is how can this be done in the template layer? Somthing like : {{ foo.bar(10) }}

like image 467
Siavash Avatar asked May 12 '26 21:05

Siavash


1 Answers

The simple answer is that you can't do this, which is by design; Django templates are designed to be keep you from writing real code in them. Instead, you'd have to write a custom filter, e.g.

@register.filter
def bar(foo, percent):
    return foo.bar( float(percent) )

This would let you make a call like {{ foo|bar:"250" }} which would be functionally identical to your (non-working example) of {{ foo.bar(250) }}.

like image 100
Eli Courtwright Avatar answered May 14 '26 11:05

Eli Courtwright