Django的内置分页类

2024-01-02 10:29:45
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger

创建分页对象,paginator = Paginator(object_list,3),每页3条数据

获取页码,request.GET.get('page')

更新当前需要展示的数据,posts = paginator.page(page)

如果page不是整数(小于1),展示第一页,posts = paginator.page(1)

如果page大于总页数,展示最后一页,posts = paginator.page(paginator.num_pages)

View代码片段如下:

from django.shortcuts import render, get_object_or_404
from .models import Post
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger

def post_list(request):
    object_list = Post.published.all()
    paginator = Paginator(object_list,3)
    page = request.GET.get('page')
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)

    template = "blog/post/list.html"
    context = {
        'page':page,
        "posts":posts,
    }
    return render(request,template,context)

创建一个模板来显示分页器,以便它可以包含在任何使用分页的模板中。

<div class="pagination">
    <span class="step-links">
        {% if page.has_previous %}
            <a href="?page={{ page.previous_page_number }}">Previous</a>
        {% endif %}
        <span class="current">
            Page {{ page.number }} of {{ page.paginator.num_pages }}.
        </span>
        {% if page.has_next %}
            <a href="?page={{ page.next_page_number }}">Next</a>
        {% endif %}
    </span>
</div>
  • page.number:当前页码
  • page.paginator.num_pages:总页数
  • page.previous_page_number:上一页码
  • page.next_page_number:下一页码

在需要展示分页的模版中调用

{% block content %}

    ...

    {% include "blog/pagination.html" with page=posts %}
{% endblock %}

📌注意模版的相对路径

文章来源:https://blog.csdn.net/Q1780020/article/details/135318767
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。