Охватываемые темы: Enabling pagination, Template with pagination, Pagination with filters, Manual pagination (in function-based views).
Enabling pagination
from django.views.generic import ListView
from .models import Task
class TaskListView(ListView):
model = Task
template_name = 'tasks/task_list.html'
context_object_name = 'tasks'
paginate_by = 20 # objects per page
ordering = ['-created_at']
Template with pagination
{% for task in tasks %}
<div>{{ task.title }}</div>
{% endfor %}
{% if is_paginated %}
<nav>
{% if page_obj.has_previous %}
<a href="?page={{ page_obj.previous_page_number }}">← Previous</a>
{% endif %}
<span>{{ page_obj.number }} / {{ page_obj.paginator.num_pages }}</span>
{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}">Next →</a>
{% endif %}
</nav>
{% endif %}
Pagination with filters
<!-- Preserve GET parameters when navigating between pages -->
<a href="?{{ request.GET.urlencode }}&page={{ page_obj.next_page_number }}">Next</a>
Manual pagination (in function-based views)
from django.core.paginator import Paginator
def task_list(request):
tasks = Task.objects.all().order_by('-created_at')
paginator = Paginator(tasks, 20)
page_number = request.GET.get('page', 1)
page_obj = paginator.get_page(page_number)
return render(request, 'tasks/list.html', {'page_obj': page_obj})
ListView context variables
| Variable | Value |
|---|---|
page_obj |
current page |
paginator |
paginator object |
is_paginated |
True if more than 1 page |
object_list |
objects on the current page |
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!