Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call function that takes an argument in a Django template?

I'm passing to Django's template a function, which returns some records. I want to call this function and iterate over its result.

{% for item in my_func(10) %}  

That doesn't work. I've tried to set the function's return value to a variable and iterate over the variable, but there seems to be no way to set a variable in a Django template.

Is there any normal way to do it?

like image 928
cleg Avatar asked Mar 18 '10 09:03

cleg


People also ask

Can I call a function in a Django template?

You cannot call a function that requires arguments in a template. Write a template tag or filter instead.

How do you call a template in Django?

To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.


2 Answers

You cannot call a function that requires arguments in a template. Write a template tag or filter instead.

like image 162
Ignacio Vazquez-Abrams Avatar answered Sep 20 '22 16:09

Ignacio Vazquez-Abrams


if you have an object you can define it as @property so you can get results without a call, e.g.

class Item:     @property     def results(self):         return something 

then in the template:

<% for result in item.results %> ... <% endfor %> 
like image 22
sherpya Avatar answered Sep 19 '22 16:09

sherpya