Passing arguments to model methods in Django templates

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 %}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)