How can I check the size of a collection within a Django template? How can I check the size of a collection within a Django template? django django

How can I check the size of a collection within a Django template?


See https://docs.djangoproject.com/en/stable/ref/templates/builtins/#if : just use, to reproduce their example:

{% if athlete_list %}    Number of athletes: {{ athlete_list|length }}{% else %}    No athletes.{% endif %}


If you're using a recent Django, changelist 9530 introduced an {% empty %} block, allowing you to write

{% for athlete in athlete_list %}  ...{% empty %}  No athletes{% endfor %}

Useful when the something that you want to do involves special treatment for lists that might be empty.


A list is considered to be False if it has no elements, so you can do something like this:

{% if mylist %}    <p>I have a list!</p>{% else %}    <p>I don't have a list!</p>{% endif %}