Skip to content

Q&A · Answered

How to add pagination to Django views

asked 9 months, 1 week ago 1298 views 1 answer
36

I have a list view with hundreds of items. How do I add pagination to show only 10 items per page?

1 Answer

One accepted
13

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago

Function-based view

from django.core.paginator import Paginator

def article_list(request):
    articles = Article.objects.all()
    paginator = Paginator(articles, 10)  # 10 per page
    
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    return render(request, 'articles/list.html', {'page_obj': page_obj})

Template pagination

<div class="pagination">
    {% if page_obj.has_previous %}
        <a href="?page={{ page_obj.previous_page_number }}">Previous</a>
    {% endif %}
    
    Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
    
    {% if page_obj.has_next %}
        <a href="?page={{ page_obj.next_page_number }}">Next</a>
    {% endif %}
</div>

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.