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

相关推荐
hboot1 小时前
AI工程师第六课 - RAG检索增强生成
后端·langchain·llm
天才测试猿2 小时前
2026软件测试面试八股文(含答案+文档)
自动化测试·软件测试·python·功能测试·测试工具·面试·职场和发展
mldong2 小时前
jeeflow:98KB 的工作流引擎长什么样
后端
张小凡vip3 小时前
python--爬虫--成熟的爬虫框架Scrapy
爬虫·python·scrapy
Pluchon3 小时前
Java个人综合项目——萌部落社区V2.0
java·python·spring·spring cloud·postman·idea
不瘦80斤不改名4 小时前
01-vibe-coding-起源与本质
人工智能·python
夜雪一千4 小时前
如何对新闻数据进行模糊去重
python
程序员cxuan5 小时前
速度太快了!本地可以跑 DeepSeek-V4-Flash 了
人工智能·后端·程序员
oyguyteggytrrwwwrt6 小时前
3dgs渲染部分详细注释
python
阿祖zu6 小时前
芝士就是力量!开源私有化部署与 GitHub 双向同步的个人知识笔记 App
前端·后端·ios