'Obtaining an item count from a list in a Django template
I am trying to get the object count on a 'list' using the length filter in the Django template and it is returning the number of characters. It looks like my list is not a real list but rather a long string. My mixin looks like this:
class ItemObjectMixin:
model = None
template_name = None
my_filter = ItemFilter
def get(self, request):
items = self.model.objects.all()
items_count = items.count()
itemsFilter = ItemsFilter(request.GET, queryset=items)
items = itemsFilter.qs
remaining = items.count()
return render(request, self.template_name, locals())
And my class-based view looks like:
class MyItemsListView(ItemObjectMixin, ListView):
model = Items
template_name = "Items/myItems.html"
My template has the following partial code:
<tbody>
{% for item in items %}
<tr>
<td><a href="/item/{{ item.slug }}">{{ item.title }}</a></td>
<td>{{ item.id }}</td>
{% if item.group_of_items %}
<td>{{ item.group_of_items|length }}</td>
{% endif %}
<td>{{ item.group_of_items }}</td>
</tr>
{% endif %}
</tbody>
The code {{ item.group_of_items|length }} gives the number of characters for each instance of 'group_of_items'. I understand why this is happening but would like a solution where the for loop gives a list of objects rather than a string. Any takers? Cheers.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
