Django-分页

定义:

InvalidPage:

page对象定义:

Page对象属性:

练习:

urls:

python 复制代码
from django.urls import path
from . import views
urlpatterns = [
    path('test_page',views.test_page)
]

views:

python 复制代码
def test_page(request):
    page_num = request.GET.get('page',1)
    all_data = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v]','w','x','y','z']
    # 初始化paginator对象
    paginator = Paginator(all_data,2)
    # 初始化具体页码的page对象
    c_page = paginator.page(int(page_num))
    return render(request,'node/test_page.html',locals())

templates.test_page:

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>分页</title>
</head>
<body>
    {% for p in c_page %}
        <p>
            {{ p }}
        </p>
    {% endfor %}

    {% if c_page.has_previous %}
        <a href="/node/test_page?page={{ c_page.previous_page_number }}">上一页</a>
    {% else %}
        上一页
    {% endif %}

    {% for i in paginator.page_range %}
        {% if i == c_page.number %}
            {{ i }}
        {% else %}
            <a href="/node/test_page?page={{ i }}">{{ i }}</a>
        {% endif %}
    {% endfor %}

    {% if c_page.has_next %}
        <a href="/node/test_page?page={{ c_page.next_page_number }}">下一页</a>
    {% else %}
        下一页
    {% endif %}
</body>
</html>

结果展示:

相关推荐
北冥you鱼21 分钟前
Go-Ethereum (Geth) 最佳实践:从部署到生产环境优化
开发语言·后端·golang
程序员爱钓鱼2 小时前
Rust 函数与返回值详解:参数、表达式与返回类型
后端·rust
hboot7 小时前
AI工程师第五课 - 大语言模型基础
python·llm·fastapi
AOwhisky7 小时前
Python 学习笔记(第一期与第二期)——基础语法——核心知识点自测与详解
开发语言·笔记·python·学习·云原生·运维开发
STLearner8 小时前
ICML 2026 | LLM×Graph论文总结[1]【图基础模型,文本属性图,多模态属性图,图对齐,图提示学习,关系深度学习
论文阅读·人工智能·python·深度学习·学习·机器学习·数据挖掘
习明然10 小时前
我的本地化AI项目(三)
人工智能·python·electron·c#·avalonia
喜欢的名字被抢了10 小时前
Python实战:SQLAlchemy ORM与FastAPI项目集成
开发语言·python·sql·教程·fastapi
夏季疯12 小时前
读论文:STARS 是什么结构?一个统一的歌声自动标注框架
python
遨游DATA12 小时前
Spring Boot 启动失败排查:如何区分多 Bean 冲突与清理阶段异常
java·spring boot·后端
IT_陈寒12 小时前
Java线程池这个坑我算是踩明白了
前端·人工智能·后端