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

相关推荐
qq_372906934 分钟前
Layui表格怎么实现在表头的右侧添加一个自定义配置图标
jvm·数据库·python
qq_3422958210 分钟前
SQL如何利用聚合函数生成业务分析指标_KPI计算基础教程
jvm·数据库·python
m0_5150984213 分钟前
SQL查询如何处理分组后的NULL值_使用COALESCE配合聚合函数
jvm·数据库·python
斯班奇的好朋友阿法法14 分钟前
本地ollama大模型速度慢的优化
python·语言模型
江山与紫云25 分钟前
1.3 使用 Jupyter Notebook
python
Metaphor69233 分钟前
使用 Python 合并 PDF 文件
java·python·pdf
亚林瓜子35 分钟前
AWS Glue PySpark中日志设置
python·spark·日志·aws·pyspark·log·glue
qq_4240985640 分钟前
HTML5中解决数据库版本号管理混乱的规范化建议
jvm·数据库·python
Sherry Wangs43 分钟前
flash-attn安装指南
pytorch·python·flash-attn
Irene19911 小时前
Python下载第三方库:requests、oracledb,连接 Oracle 数据库,测试数据输出(切记不要操作或删除系统表)
数据库·python·oracledb