django 分页

在做分页前,先把所有的博客在网页中显示出来

在bloguser/views.py中添加welcome方法

def welcome(request):

    blogSet = Blog.objects.values('id','title',createTime','blogUser__username').all()

    return render(request,'welcome.html',{'user':request.session.get('user',None),'blogSet':blogSet})

在templates/welcome.htm中把要显示的内容用循环遍历出来

{% for blog in blogSet %}

    <div>

        <a href="/blog/show/{{ blog.id }}">{{ blog.title }}</a> 作者:{{ blog.blogUser__username }} 发表时间:{{ blog.createTime | date:'Y年m月d日 H:i:s' }}

{% endfor %}

在这里的a标签会以GET方式跳转到blog/show, 显示全部的内容,按以下方式

<body>
{{ blog.title }}<br />
{{ blog.createTime | date:'Y-m-d H:i:s'}}<br />
{{ blog.blogUser.username }}<br />
{{ blog.content }}
{% autoescape off %}
    {{ blog.content }}
{% endautoescape %}
</body>

现在分页,先要导入模块在bloguser/views.py中

from django.core import paginator

def welcome(request):

    blogSet = Blog.objects.values('id','tatle','createTime','blogUser__username').all()

    pageNum = int(request.GET.get('pageNum',1))  #确定页数

    page = paginator.Paginator(blogSet,5)  #确定每页有几条信息

    isFirstPage = (pageNum == 1)  #确定第一页

    isLastPage = (pageNum == page.num_pages)  #确定尾页

    return render(request.'welcome.html',{'user':request.session.get('user',None),'blogSet':page.get_page(pageNum),

        'ppageNum':pageNum-1,'npageNum':pageNum+1,'isFirstPage':isFirstPage,'isLastPage':isLastPage,'totalPage':

        page.num_pages})

'ppageNum':pageNum-1, 是定义上一页     npageNum':pageNum+1, 是定义下一页

在templates/welcome.htm中添加需要在网页中显示的链接 首页  上一页  下一页 尾页

{% if not isFirstPage %}  #这里的判断,如果不是首页会显示 首页和上一页

    <a href="welcome?pageNum=1">首页</a>

    <a href="welcome?pageNum={{ ppageNum }}">上一页</a>

{% endif %}

{% if not isLastPage %}  #这里的判断,如果不是尾页会显示 尾页和下一页

    <a href="welcome?pageNum={{ npageNum }}">下一页</a>

    <a href="welcome?pageNum={{ totalPage }}">尾页</a>

{% endif %}

如果以上两个条件都不存在,那么就全部显示












  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值