Django专门提供了一个paginator模块,实现分页很easy。

下面的例子引用了django官方文档:https://docs.djangoproject.com/en/1.11/topics/pagination/

使用Paginator类

Paginator实例化需要2个参数,一个是待分页的对象list(需要实现count方法或者__len__方法),另一个是每页数量。 
Paginator对象属性:

count 对象数量
num_pages 总页数
page_range 所有页数范围的生成器
>>> from django.core.paginator import Paginator
>>> objects = ['john', 'paul', 'george', 'ringo']
>>> p = Paginator(objects, 2) >>> p.count
4
>>> p.num_pages
2
>>> type(p.page_range)
<class 'range_iterator'>
>>> p.page_range
range(1, 3)

Paginator对象的重要方法,page(),接受一个页码作为参数,返回一个当前页对象。该对象的几个属性和方法:

object_list 当前页的对象列表
has_next() 有无下一页
has_ previous() 有无上一页
has_other_pages() 有无其他页
next_page_number() 下一页页码
previous_page_number() 上一页页码
start_index() 返回当前页第一个对象的在所有对象中的索引,注意,从1开始
end_index() 返回当前页最后一个对象在所有对象中的索引,注意,从1开始
paginator 所关联的Paginator对象
>>> page1 = p.page(1)
>>> page1
<Page 1 of 2>
>>> page1.object_list
['john', 'paul'] >>> page2 = p.page(2)
>>> page2.object_list
['george', 'ringo']
>>> page2.has_next()
False
>>> page2.has_previous()
True
>>> page2.has_other_pages()
True
>>> page2.next_page_number()
Traceback (most recent call last):
...
EmptyPage: That page contains no results
>>> page2.previous_page_number()
1
>>> page2.start_index() # The 1-based index of the first item on this page
3
>>> page2.end_index() # The 1-based index of the last item on this page
4

Pagenator的page方法,若传给一个无页码范围之外都值,则得到一个EmptyPage的异常。

>>> p.page(0)
Traceback (most recent call last):
...
EmptyPage: That page number is less than 1
>>> p.page(3)
Traceback (most recent call last):
...
EmptyPage: That page contains no results

在视图中可以这么用:

# views.py
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render def listing(request):
contact_list = Contacts.objects.all()
paginator = Paginator(contact_list, 25) # 每页显示25个 page = request.GET.get('page') # 拿到页码参数
try:
contacts = paginator.page(page)
except PageNotAnInteger:
# 捕获到页码不是整数,返回第一页
contacts = paginator.page(1)
except EmptyPage:
# 页码超出范围,返回最后一页
contacts = paginator.page(paginator.num_pages) return render(request, 'list.html', {'contacts': contacts})

contacts对象是用带有分页信息的QuerySet,用来渲染模板:list.html

{% for contact in contacts %}
{# Each "contact" is a Contact model object. #}
{{ contact.full_name|upper }}<br />
...
{% endfor %} <div class="pagination">
<span class="step-links">
{% if contacts.has_previous %}
<a href="?page={{ contacts.previous_page_number }}">previous</a>
{% endif %} <span class="current">
Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}.
</span> {% if contacts.has_next %}
<a href="?page={{ contacts.next_page_number }}">next</a>
{% endif %}
</span>
</div>

基于模型类的视图,只需给paginate_by赋值(每页个数)就可以了,似乎是更简单:

class BookListView(generic.ListView):
model = Book
context_object_name = 'book_list'
template_name = 'catalog/book_list.html'
paginate_by = 10

模板是通用的,在模板中,可以调用is_paginated 判断是否有分页信息。在用page_obj对象实现分页。

{% block pagination %}
{% if is_paginated %}
<div class="pagination">
<span class="pagelinks">
{% if page_obj.has_previous %}
<a href="{{ request.path }}?page={{ page_obj.previous_page_number }}">previous</a>
{% endif %}
<span class="page-current">
Page{{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
<a href="{{ request.path }}?page={{ page_obj.next_page_number }}">next</a>
{% endif %}
</span>
</div>
{% endif %}
{% endblock %}

Django-利用paginator模块实现分页的更多相关文章

  1. Django 之 Paginator 分页功能

    Django Paginator Django 分页官方文档  https://docs.djangoproject.com/en/1.10/topics/pagination/ 此分页方法没有限制显 ...

  2. Django 利用 Pagination 简单分页

    Django自身提供了一些类来实现管理分页,数据被分在不同的页面中,并带有“上一页/下一页”标签.这个类叫做Pagination,其定义位于 django/core/paginator.py 中. 一 ...

  3. 利用Django做一个简单的分页页面

    views代码: from django.shortcuts import render from django.conf import settings from booktest.models i ...

  4. Django 利用 Pagination 分页

    Django自身提供了一些类来实现管理分页,数据被分在不同的页面中,并带有“上一页/下一页”标签.这个类叫做Pagination,其定义位于 django/core/paginator.py 中. 一 ...

  5. Django 使用Paginator分页

    from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger subclass_s = models.subclas ...

  6. django基础之Ajax、分页、cookie与session

    目录: Ajax之json Ajax简介 jquery实现的ajax js实现的ajax django分页器 COOKIE与SESSION 一.Ajax之json 1.什么是json? 定义: JSO ...

  7. Django Cookie Session和自定义分页

    Django中操作Cookie 获取Cookie request.COOKIES['key'] request.get_signed_cookie(key, default=RAISE_ERROR, ...

  8. Django(二十)分页:

    一.知识点 参考:https://docs.djangoproject.com/zh-hans/3.0/topics/pagination/ 查询出所有省级地区的信息,显示在页面上. AeroInfo ...

  9. Django 学习笔记之七 实现分页

    接着上篇,在上篇的基础上实现网页数据分页显示 1.打开views.py,编辑如下 #coding:utf-8from django.shortcuts import render,get_object ...

随机推荐

  1. Face alignment at 3000FPS via Regressing Local Binrary features 理解

    这篇是Ren Shaoqing发表在cvpr2014上的paper,论文是在CPR框架下做的,想了解CPR的同学可以参见我之前的博客,网上有同学给出了code,该code部分实现了LBF,链接为htt ...

  2. bzoj 1594: [Usaco2008 Jan]猜数游戏【二分+线段树】

    写错一个符号多调一小时系列-- 二分答案,然后判断这个二分区间是否合法: 先按值从大到小排序,然后对于值相同的一些区间,如果没有交集则不合法:否则把并集在线段树上打上标记,然后值小于这个值的区间们,如 ...

  3. iOS 关于文件操作 NSFileManager

    创建文件夹 + (BOOL)creatDir:(NSString *)path { if (path.length==0) { return NO; } NSFileManager *fileMana ...

  4. ElementaryOS 0.4快速配置工具

    使用方法: 终端执行 wget http://linux-1251056822.costj.myqcloud.com/elementary_config && bash element ...

  5. FFT学习及简单应用(一点点详细)

    什么是FFT 既然打开了这篇博客,大家肯定都已经对FFT(Fast Fourier Transformation)有一点点了解了吧 FFT即为快速傅里叶变换,可以快速求卷积(当然不止这一些应用,但是我 ...

  6. 2、ipconfig命令

    该命令能够显示出正在使用的计算机的IP信息情况.这些信息包括IP地址.子网掩码.默认网关(连接本地计算机与Internet的计算机).通过IP地址可以进行扫描.远程管理.入侵检测等.ipconfig命 ...

  7. Selenium常用方法及函数

    新建实例driver = webdriver.Chrome() 1.获取当前页面Url的函数方法:current_url实例:driver.current_url 2.表单的提交方法:submit解释 ...

  8. dedecms手机网站内页上一篇/下一篇的翻页功能

    修改文件include/arc.archives.class.php文件. 1.搜索 function GetPreNext($gtype='') 2.将这个函数的所有内容替换为 function G ...

  9. 北大ACM(POJ1017-Packets)

    Question:http://poj.org/problem?id=1017 问题点:贪心. Memory: 224K Time: 32MS Language: C++ Result: Accept ...

  10. 使用Spring框架的步骤

    “好记性,不如烂笔头”.今天正式接触了Spring框架,第一次接触Spring框架感觉Spring框架简化了好多程序代码,开发效率大大提高.现在介绍使用Spring框架的步骤.(使用spring-fr ...