Passing arguments to model methods in Django templates

django

Solution

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

Problem

I'm trying to get all customers from a specified business, but there is a class method in Customer model to get some information based on the same Business... Let me explain this with code... ``` class Business(models.Model): ... customers = models.ManyToManyField(Customer, blank=True, null=True) class Customer(models.Model): ... def get_something(self, obj_business) ... ``` Ok now in my views I get all customers from a specified business like this: ``` obj_customers = obj_business.customers.all() ``` Then I try to print this in my template: ``` {% for obj_customer in obj_customers %} {{ obj_customer.get_something ....... }} ``` But yes, there is not a way to pass arguments... I would like to know if there is something that I'm missing... I wonder if there is another solution instead creating a template tag... because it is a ManyToManyField, if customers field had been just ForeignKey, no need to pass an argument to that method...

Original source