Django — Pagination
Basic Pagination
from django.core.paginator import Paginator
def post_list(request):
posts = Post.objects.all()
paginator = Paginator(posts, 10) # 10 per page
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request, 'blog/list.html', {'page_obj': page_obj})
Template
<div class="pagination">
{% if page_obj.has_previous %}
<a href="?page=1">« First</a>
<a href="?page={{ page_obj.previous_page_number }}">Previous</a>
{% endif %}
<span>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</span>
{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}">Next</a>
<a href="?page={{ page_obj.paginator.num_pages }}">Last »</a>
{% endif %}
</div>
Paginator Methods
| Method | Description |
|---|---|
| get_page() | Get page safely |
| num_pages | Total pages |
| page_range | Range of page numbers |
| count | Total items |
Page Methods
| Method | Description |
|---|---|
| has_previous() | Has previous page |
| has_next() | Has next page |
| previous_page_number() | Previous page number |
| next_page_number() | Next page number |
| object_list | Items on page |
Mini Practice
- Paginate a queryset
- Create pagination template
- Handle page navigation
- Style pagination links
Up Next
Continue with Class-Based Views — using class-based views.
Related Topics
Frequently Asked Questions about Pagination
What is Pagination in Django?
Pagination is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Pagination?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Pagination.
Why is Pagination important in Django?
Pagination is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.