Sobes.tech
Junior — Middle

How to implement a data pagination mechanism in the Django framework?

sobes.tech AI

Answer from AI

In Django, the built-in Paginator class from the django.core.paginator module is used to implement pagination.

Example of usage:

from django.core.paginator import Paginator
from django.shortcuts import render
from .models import Article

def article_list(request):
    article_list = Article.objects.all()
    paginator = Paginator(article_list, 10)  # show 10 articles 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})

In the template, you can use the page_obj object to display the current page's items and navigation:

{% for article in page_obj %}
  <h2>{{ article.title }}</h2>
  <p>{{ article.content }}</p>
{% endfor %}

<div class="pagination">
  {% if page_obj.has_previous %}
    <a href="?page={{ page_obj.previous_page_number }}">Back</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>
  {% endif %}
</div>

Thus, Paginator makes it easy to split a dataset into pages and manage navigation between them.

How to implement a data pagination mechanism in the… - sobes.tech