Pagination is a common feature in web applications that display large amounts of data. It allows users to navigate through the data in smaller, more manageable chunks, rather than having to load all of the data at once. Django provides built-in support for pagination through its Paginator class.
Here's a basic example of how to use pagination in Django
import paginatior class
First, import the Paginator class from the django.core.paginator module:
from django.core.paginator import Paginator
Writing view
In your view function, retrieve the data you want to paginate from the database:
def my_view(request):
data = MyModel.objects.all()
# rest of the view code
Create paginator object
Create a Paginator object with the data and the number of items to display per page:
def my_view(request):
data = MyModel.objects.all()
paginator = Paginator(data, 10) # 10 items per page
# rest of the view code
Get page
Get the current page number from the request's GET parameters and use it to get a slice of the data for the current page:
def my_view(request):
data = MyModel.objects.all()
paginator = Paginator(data, 10) # 10 items per page
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
# rest of the view code
set context
Pass the page_obj to your template context along with any other data you want to display:
def my_view(request):
data = MyModel.objects.all()
paginator = Paginator(data, 10) # 10 items per page
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
context = {
'page_obj': page_obj,
# other context data
}
return render(request, 'my_template.html', context)
Display Data
In your template, loop over the page_obj to display the items on the current page, and use the page_obj's has_previous(), has_next(), and paginator.num_pages attributes to generate pagination links:
{% for item in page_obj %}
<!-- display item here -->
{% endfor %}
<div class="pagination">
{% if page_obj.has_previous %}
<a href="?page={{ page_obj.previous_page_number }}">previous</a>
{% endif %}
<span class="current-page">{{ page_obj.number }}</span>
{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}">next</a>
{% endif %}
<span class="total-pages">of {{ paginator.num_pages }}</span>
</div>
That's it! This example should give you a good starting point for implementing pagination in your Django project.