Django分页

1、在视图函数文件中引入'分页器'

python 复制代码
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

2、给原来的罗列信息函数,添加分页功能,即按照页码,只返回部分信息。

python 复制代码
@login_required
def article_list(request):
    articles_list = ArticlePost.objects.filter(author=request.user)
    #根据查询的articles_list创建分页对象,每页3个
    paginator = Paginator(articles_list, 3)
    #获得GET请求的参数:page的值,也就是页码数
    page = request.GET.get('page')
    try:
        current_page = paginator.page(page)#按照页码,使用分页器的page方法得到页面内容
        articles = current_page.object_list#得到页面内容的对象列表
    except PageNotAnInteger:#如果请求的页码不是整数
        current_page = paginator.page(1)#返回第一页
        articles = current_page.object_list
    except EmptyPage:#如果页码值为空,或URL参数中没有page
        current_page = paginator.page(paginator.num_pages)#返回最后一页
        articles = current_page.object_list


    context = {'articles': articles, 'page':current_page}
    return render(request, 'article/column/article_list.html', context)

3、向项目的根templates中添加paginator.html模板,用于在需要分页的地方include

注意在写href时,问号和page之间没有空格

html 复制代码
<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>

4、在原来的罗列信息页面中,引入分页模板

html 复制代码
<table>
...
</table>
    {% include "paginator.html" %}

5、运行结果如下

相关推荐
万少23 分钟前
万少的博客 - 技术分享与解决方案
前端·javascript·后端
咖啡八杯34 分钟前
GoF设计模式——备忘录模式
java·后端·spring·设计模式
苍何44 分钟前
腾讯再放大招,企微 Agent 大圆开启内测
后端
ethantan1 小时前
一篇讲解AI Agent 组成:像人一样思考的智能体
人工智能·后端·程序员
apocelipes3 小时前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
Cosolar3 小时前
vLLM 生产级部署完全指南
人工智能·后端·架构
IT_陈寒3 小时前
垃圾回收器选错了,我的Java服务内存炸了
前端·人工智能·后端
用户8356290780514 小时前
使用 Python 在 PDF 中创建与管理书签
后端·python
Nturmoils4 小时前
字段太多看不全,ksql 的展开模式和输出控制怎么用
数据库·后端
大志说编程4 小时前
Agent面试真题06: 十分钟带你快速掌握Agent记忆管理高频面试题(附详细答案)
后端·面试·ai编程