Reputation: 4008
I want to generate a range of pages in my template when using a ListView
and it's pagination
, to generate dynamically the number of pages for the pagination:
https://getbootstrap.com/docs/4.0/components/pagination/
My first attempt was to make a for loop for everyelement in page_obj.paginator.num_pages
, getting error int is not iterable
:
{% if is_paginated %}
<ul class="pagination">
{% for i in page_obj.paginator.num_pages %}
<li class="page-item">
<span class="page-link">
<a href="/catalogo?page={{i}}">
<span class="sr-only">(current)</span>
</span>
</li>
{% endfor %}
</ul>
{% endif }
Then I've discovered that there isn't and wont be a range template filter because this calculation should be done in the view and send the range to the template, not generated in the template
. See:
https://code.djangoproject.com/ticket/13088
So how can I access the
page_obj.paginator.num_pages
inside the view???
My LisView:
class CatalogoListView(ListView):
model = UnitaryProduct
template_name = "shop/catalogo.html"
paginate_by = 10
def get_queryset(self):
filter_val = self.request.GET.get('filtro', 'todas')
order = self.request.GET.get('orderby', 'created')
if filter_val == "todas":
context = UnitaryProduct.objects.all().filter(available=True).order_by('-created')
return context
else:
context = UnitaryProduct.objects.filter(
subcategory2=filter_val,
).filter(available=True).order_by('-created')
return context
def get_context_data(self, **kwargs):
context = super(CatalogoListView, self).get_context_data(**kwargs)
context['filtro'] = self.request.GET.get('filtro', 'todas')
context['orderby'] = self.request.GET.get('orderby', 'created')
context['category'] = Category.objects.get(slug="catalogo")
return context
Upvotes: 2
Views: 303
Reputation: 4160
num_pages
is an integer storing the total number of pages, thus not iterable.
What you are looking for is page_range
, which is a list of page numbers.
You can iterate on it from your template, just replace
{% for i in page_obj.paginator.num_pages %}
with
{% for i in page_obj.paginator.page_range %}
Upvotes: 4