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、运行结果如下

相关推荐
是上好佳佳佳呀6 小时前
【Python基础|DAY05】Python 模块与包
python
大数据魔法师6 小时前
Streamlit(十一)- API 参考文档(四)- 图表元素
python·web
AllData公司负责人6 小时前
亲测丝滑,体验跃迁|AllData通过集成开源项目Datart,让数据可视化一目了然
java·大数据·数据库·python·数据可视化·数据视图·datart
tang777897 小时前
2026代理IP选型逻辑与成本控制:动态IP VS 静态IP、住宅IP VS 运营商IP VS 数据中心IP的深入解析
爬虫·python·代理ip·住宅ip·住宅代理·运营商ip
古城小栈7 小时前
Rust Tauri:构建轻量高性能跨平台桌面应用
开发语言·后端·rust
AI玫瑰助手7 小时前
Python函数:def定义函数与参数传递基础
android·开发语言·python
染翰7 小时前
Linux root用户安装配置Git
linux·git·后端
24kmaigc7 小时前
NewStarCTF2025-ssti在哪里?-ssrf与ssti注入
python·网络安全·flask·web
老虎海子7 小时前
从零手搓一个 AI 编程助手:Mini Claude Code 完全指南
人工智能·git·vscode·python·github
正在走向自律7 小时前
金仓数据库DISTINCT优化:从全表扫描到LIMIT 1的蜕变
后端