How to implement pagination in Django?

Implementing pagination in Django typically requires using the built-in pagination module django.core.paginator.Paginator. Here is a simple example:

  1. Import the Paginator module in the view function.
from django.core.paginator import Paginator
  1. Implement pagination logic in the view function.
def my_view(request):
    # 获取数据,这里假设数据存储在items列表中
    items = MyModel.objects.all()

    # 每页显示的数量
    per_page = 10

    # 创建Paginator实例
    paginator = Paginator(items, per_page)

    # 获取当前页数
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    return render(request, 'my_template.html', {'page_obj': page_obj})
  1. the HTML template belongs to me
{% 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 steps above, you can implement basic pagination in Django.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds