Reputation: 368
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) }}
Upvotes: 3
Views: 308
Reputation: 118458
Just do this calculation in the view, and not the template.
This is often the solution to many "template language can't do X" problems.
foo = Foo(number=250)
foo.bar = foo.bar(10)
return direct_to_template(request, "foo.html", {'foo': foo})
{{ foo.bar }}
Upvotes: 0
Reputation: 192921
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) }}
.
Upvotes: 4
Reputation: 8066
By design, Django templates don't allow you to invoke methods directly so you'd have to create a custom template tag to do what you want.
Jinja2 templates do allow you to invoke methods, so you could look into integrating Jinja2 with Django as another option.
Upvotes: 1