源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Django实现快速分页的方法实例

  • 时间:2020-02-08 06:46 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Django实现快速分页的方法实例
[b]前言[/b] 本文主要给大家介绍了关于Django快速分页的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。 [img]http://files.jb51.net/file_images/article/201710/20171022141949453.jpg?2017922142020[/img] 分页 在web开发中,对大量的商品进行分页显示,是常见的需求,django对分页直接提供了现成的函数,让我们的开发更为快速便捷... [img]http://files.jb51.net/file_images/article/201710/20171022142036130.gif?2017922142048[/img] 动图_Django快速分页 [b]示例代码:[/b] 在后端(视图函数中)
from django.shortcuts import render
from .models import ShowMyComputer
# 引入方法
from django.core.paginator import Paginator
# Create your views here.

def show(request, page_id):

 # 获取需要分页的对象集合
 all_goods = ShowMyComputer.objects.all()

 # 创建分页对象
 paginator = Paginator(all_goods, 3)

 # 根据当前页码,确定返回的数据
 current_page = paginator.page(page_id)

 # 保证前端取到的"页数"为整型
 page_id = int(page_id)


 return render(request, 'computer/list.html', locals())
在前端(html模板中)
<body>
 {# 展示当前页面的数据 #}
 {% for goods in current_page %}
 <div class="my_goods">

  <div class="goods_image">  
   ![图片占位](/static/{{ goods.goods_image }})
  </div>
  
  <br>
  
  <div class="goods_name">{{ goods.goods_name }}</div>

 </div>

 {% endfor %}


 <div class="page_num">

 {# 判断'上一页'是否存在,如果存在则保留`上一页`标签 ,反之则不显示`上一页`标签 #}
 {% if current_page.has_previous %}

  <a href="{% url 'computer:show' current_page.previous_page_number %}" rel="external nofollow" >上一页</a>

 {% endif %}


 {# 确定分页数量 #}

 {% for index in paginator.page_range %}

  {# 如果页码与当前页面相符,则添加红色背景 #}
 {% if page_id == index %}
  <a href= "{% url 'computer:show' index %}" style="background-color: red" >{{ index }}</a>
  {# 如果页面与当前页面不符,则正常显示 #}
 {% else %}
  <a href="{% url 'computer:show' index %}" rel="external nofollow" >{{ index }}</a>
 {% endif %}

 {% endfor %}

 {# 判断'下一页'是否存在,如果存在则保留`下一页`标签 ,反之则不显示`下一页`标签 #}
 {% if current_page.has_next%}

  <a href="{% url 'computer:show' current_page.next_page_number %}" rel="external nofollow" >下一页</a>

 {% endif %}


 </div>

</body>
[b]总结[/b] 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对编程素材网的支持。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部