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

yipeiwu_com5年前Python基础

前言

本文主要给大家介绍了关于Django快速分页的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

分页

在web开发中,对大量的商品进行分页显示,是常见的需求,django对分页直接提供了现成的函数,让我们的开发更为快速便捷...

动图_Django快速分页

示例代码:

在后端(视图函数中)

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>

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

python的xpath获取div标签内html内容,实现innerhtml功能的方法

python的xpath没有获取div标签内html内容的功能,也就是获取div或a标签中的innerhtml,写了个小程序实现一下: 源代码 [webadmin@centos7 c...

python list数据等间隔抽取并新建list存储的例子

原始数据如下: ['e3cd', 'e547', 'e63d', '0ffd', 'e39b', 'e539', 'e5be', '0dd2', 'e3d6', 'e52e', 'e...

Python3.6.2调用ffmpeg的方法

本文是为了学习python调用C语言的库写的例子。 去ffmpeg官网下载编译好的avcodec-57.dll、avutil-55.dll、swresample-2.dll,准备好了C语...

python根据出生日期返回年龄的方法

本文实例讲述了python根据出生日期返回年龄的方法。分享给大家供大家参考。具体实现方法如下: def CalculateAge(self, Date): '''Calcul...

Python装饰器的执行过程实例分析

本文实例分析了Python装饰器的执行过程。分享给大家供大家参考,具体如下: 今天看到一句话:装饰器其实就是对闭包的使用,仔细想想,其实就是这回事,今天又看了下闭包,基本上算是弄明白了闭...