[Django]-Passing arguments to model methods in Django templates

58๐Ÿ‘

You can create a simple template tag to call any method with any arguments:

from django import template

register = template.Library()

@register.simple_tag
def call_method(obj, method_name, *args):
    method = getattr(obj, method_name)
    return method(*args)

And then in your template:

{% call_method obj_customer 'get_something' obj_business %}

But, of course, crating of a specialized template tag is more safe ๐Ÿ™‚

@register.simple_tag
def get_something(customer, business):
    return customer.get_something(business)

Template:

{% get_something obj_customer obj_business %}
๐Ÿ‘คcatavaran

4๐Ÿ‘

You cannot pass arguments to functions in Django templates.

Instead you can write your own template tag.

Here are some examples:

https://github.com/miohtama/LibertyMusicStore/blob/master/tatianastore/templatetags/content.py

๐Ÿ‘คMikko Ohtamaa

Leave a comment