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...
And this is rather simple, because Django has built-in template modules that makes a transfer easy. Basically you just take the variable from views.py and enclose it within curly braces {{ }} in the template file.
You cannot call a function that requires arguments in a template. Write a template tag or filter instead.
{% extends variable %} uses the value of variable . If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.
What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.
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 %}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With