I'm following the tutorial in the Django documentation, and experimenting with models and views. I have a Person model, which has a many-to-many relationship to other Persons, which I call "friends". I wanted to show a list of people in my database, and their friends, so I tried the following template:
{% if people %}
<ul>
{% for p in people %}
<li>
{{ p.name }}
<ul>
{% for f in p.friends.all() %}
<li>
{{ f.name }}
</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
{% else %}
<p>There are no people.</p>
{% endif %}
Django tells me that it cannot find the all() method. In a wild guess I try to take away the parentheses, leaving the line as follows {% for f in p.friends.all %}. To my surprise, this actually works, but I cannot understand why.
Am I actually calling the method and getting a query set back, or is something completely different going on?
As Victor Castillo Torres points out in a comment, in Django templates you do not include parentheses in method calls. Only methods without parameters can be called, and these are called without parentheses.
Further details in the Django documentation: https://docs.djangoproject.com/en/dev/topics/templates/#variables
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