Chris
Chris

Reputation: 379

Counting items in Django templates

Is it possible to tally items being listed as part of the django template within the html?

For example, I have a django template with the following code snippet in it:

<div>
   {% for thing in thing_list %}
      {% if thing.status == "n" %}
         <a>{{ thing.status.count }}</a>
      {% endif %}
   {% endfor %}
</div>

This django template displays all of the things in a list, and I can call each attribute of the thing and display it, so I know I have access to all of the fields.

I want to count then number of "things" and display that number as text. My current attempt above isn't working. Does anyone have any suggestions?

Upvotes: 1

Views: 4977

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599470

As Willem says, you should do this in the view. Rather than passing a list of all Things and then checking their status in the template with if, you should filter your Things when querying them from the database in the first place:

thing_list = Thing.objects.filter(status='n')

Then you can do just {{ thing_list.count }} in the template.

Upvotes: 5

Related Questions