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

相关推荐
青柠代码录2 分钟前
【Spring】@Component VS @Configuration
后端
zhuhezhang6 分钟前
一个用python开发的文本对比工具
python·文本对比工具
智算菩萨7 分钟前
【Python图像处理】5 Pillow图像处理与格式转换
图像处理·python·pillow
人工干智能16 分钟前
科普:%%matplotlib inline:魔法命令 (Cell Magic)
python·matplotlib
05大叔18 分钟前
优化器Adam,神经网络处理文本,CNN,RNN
开发语言·python·机器学习
徒 花41 分钟前
Python知识学习08
java·python·算法
喵个咪1 小时前
go-wind-cms 微服务架构设计:为什么基于 Kratos?
后端·微服务·cms
神奇小汤圆1 小时前
百度面试官:Redis 内存满了怎么办?你有想过吗?
后端
喵个咪1 小时前
Headless 架构优势:内容与展示解耦,一套 API 打通全端生态
前端·后端·cms
开心就好20251 小时前
HTTPS超文本传输安全协议全面解析与工作原理
后端·ios