How can we implement pagination to display data in Django?

In Django, you can utilize the built-in Paginator to implement pagination for displaying data. Below is a simple example code:

  1. Firstly, import the Paginator and Page classes.
from django.core.paginator import Paginator, Page
  1. Firstly, in the view function, query the data that needs to be displayed.
from .models import YourModel

def your_view(request):
    data = YourModel.objects.all()
  1. Create a Paginator object and specify the number of items to display per page.
paginator = Paginator(data, 10)  # 每页显示10条数据
  1. Get the current page number and based on it, retrieve the data for that page.
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
  1. Pass the paginated data to the template for rendering.
return render(request, 'your_template.html', {'page_obj': page_obj})
  1. Use the properties and methods of Paginator in the template to display paginated data.
{% for item in page_obj %}
    <!-- 显示item的内容 -->
{% endfor %}

<!-- 显示分页链接 -->
<div class="pagination">
    <span class="step-links">
        {% if page_obj.has_previous %}
            <a href="?page=1">&laquo; first</a>
            <a href="?page={{ page_obj.previous_page_number }}">previous</a>
        {% endif %}

        <span class="current">
            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 &raquo;</a>
        {% endif %}
    </span>
</div>

By following the above steps, you can implement pagination for displaying data in Django using Paginator.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds