33

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...

2 Answers 2

57

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.