Niladry Kar
Niladry Kar

Reputation: 1203

How to show page items count in django pagination for CBV?

I'm trying to figure out how to show something like "Showing 1-10 of 52" using django pagination in my templates.

I am using CBV for my application.

This is what I have done

In my views.py:

class viewbloglistview(LoginRequiredMixin,ListView):
    model = Blog
    paginate_by = 6

And in my template:

{% if is_paginated %}
      <ul class="pagination">
       {% if page_obj.has_previous %}
           <li><a href="?page={{ page_obj.previous_page_number }}">Previous</a></li>
       {% else %}
            <li class="disabled"><span>Previous</span></li>
       {% endif %}
       {% for i in paginator.page_range %}
         {% if page_obj.number == i %}
             <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
         {% else %}
              <li><a href="?page={{ i }}">{{ i }}</a></li>
         {% endif %}
       {% endfor %}
          {% if page_obj.has_next %}
             <li><a href="?page={{ page_obj.next_page_number }}">Next</a></li>
          {% else %}
               <li class="disabled"><span>Next</span></li>
       {% endif %}
      </ul>
{% endif %}

Any ideas anyone how this can be accomplished in django?

Thank you

Upvotes: 1

Views: 645

Answers (1)

Jorge Cosgayon
Jorge Cosgayon

Reputation: 11

You can get the count of your queryset and add to your existing context like this in your views.py:

def get_context_data(self, *, object_list=None, **kwargs):
    context = super().get_context_data(**kwargs)
    context['total'] = self.get_queryset().count
    return context

Upvotes: 1

Related Questions