django-pure-pagination

django分页插件

插件GitHub地址:https://github.com/jamespacileo/django-pure-pagination

介绍

django应用程序提供了先进的分页功能,而不会在现有项目中强制进行主要的代码更改。

Django纯分页是基于Django的核心分页模块,因此与现有的api兼容。Django核心分页模块的文档

  1 Paginator objects 
  2 
  3 The Paginator class has this constructor:
  4 
  5 class Paginator(object_list, per_page, orphans=0, allow_empty_first_page=True)[source] 
  6 Required arguments 
  7 
  8 object_list
  9 A list, tuple, QuerySet, or other sliceable object with a count() or __len__() method. For consistent pagination, QuerySets should be ordered, e.g. with an order_by() clause or with a default ordering on the model.
 10 
 11 Performance issues paginating large QuerySets
 12 
 13 If you’re using a QuerySet with a very large number of items, requesting high page numbers might be slow on some databases, because the resulting LIMIT/OFFSET query needs to count the number of OFFSET records which takes longer as the page number gets higher.
 14 per_page
 15 The maximum number of items to include on a page, not including orphans (see the orphans optional argument below).
 16 Optional arguments 
 17 
 18 orphans
 19 Use this when you don’t want to have a last page with very few items. If the last page would normally have a number of items less than or equal to orphans, then those items will be added to the previous page (which becomes the last page) instead of leaving the items on a page by themselves. For example, with 23 items, per_page=10, and orphans=3, there will be two pages; the first page with 10 items and the second (and last) page with 13 items. orphans defaults to zero, which means pages are never combined and the last page may have one item.
 20 allow_empty_first_page
 21 Whether or not the first page is allowed to be empty. If False and object_list is empty, then an EmptyPage error will be raised.
 22 Methods 
 23 
 24 Paginator.get_page(number)[source] 
 25 New in Django 2.0.
 26 Returns a Page object with the given 1-based index, while also handling out of range and invalid page numbers.
 27 
 28 If the page isn’t a number, it returns the first page. If the page number is negative or greater than the number of pages, it returns the last page.
 29 
 30 It raises an exception (EmptyPage) only if you specify Paginator(..., allow_empty_first_page=False) and the object_list is empty.
 31 
 32 Paginator.page(number)[source] 
 33 Returns a Page object with the given 1-based index. Raises InvalidPage if the given page number doesn’t exist.
 34 
 35 Attributes 
 36 
 37 Paginator.count 
 38 The total number of objects, across all pages.
 39 
 40 Note
 41 
 42 When determining the number of objects contained in object_list, Paginator will first try calling object_list.count(). If object_list has no count() method, then Paginator will fallback to using len(object_list). This allows objects, such as Django’s QuerySet, to use a more efficient count() method when available.
 43 Paginator.num_pages 
 44 The total number of pages.
 45 
 46 Paginator.page_range 
 47 A 1-based range iterator of page numbers, e.g. yielding [1, 2, 3, 4].
 48 
 49 InvalidPage exceptions 
 50 
 51 exception InvalidPage[source] 
 52 A base class for exceptions raised when a paginator is passed an invalid page number.
 53 
 54 The Paginator.page() method raises an exception if the requested page is invalid (i.e., not an integer) or contains no objects. Generally, it’s enough to catch the InvalidPage exception, but if you’d like more granularity, you can catch either of the following exceptions:
 55 
 56 exception PageNotAnInteger[source] 
 57 Raised when page() is given a value that isn’t an integer.
 58 
 59 exception EmptyPage[source] 
 60 Raised when page() is given a valid value but no objects exist on that page.
 61 
 62 Both of the exceptions are subclasses of InvalidPage, so you can handle them both with a simple except InvalidPage.
 63 
 64 
 65 
 66 
 67 Page objects 
 68 
 69 You usually won’t construct Page objects by hand – you’ll get them using Paginator.page().
 70 
 71 class Page(object_list, number, paginator)[source] 
 72 A page acts like a sequence of Page.object_list when using len() or iterating it directly.
 73 
 74 Methods 
 75 
 76 Page.has_next()[source] 
 77 Returns True if there’s a next page.
 78 
 79 Page.has_previous()[source] 
 80 Returns True if there’s a previous page.
 81 
 82 Page.has_other_pages()[source] 
 83 Returns True if there’s a next or previous page.
 84 
 85 Page.next_page_number()[source] 
 86 Returns the next page number. Raises InvalidPage if next page doesn’t exist.
 87 
 88 Page.previous_page_number()[source] 
 89 Returns the previous page number. Raises InvalidPage if previous page doesn’t exist.
 90 
 91 Page.start_index()[source] 
 92 Returns the 1-based index of the first object on the page, relative to all of the objects in the paginator’s list. For example, when paginating a list of 5 objects with 2 objects per page, the second page’s start_index() would return 3.
 93 
 94 Page.end_index()[source] 
 95 Returns the 1-based index of the last object on the page, relative to all of the objects in the paginator’s list. For example, when paginating a list of 5 objects with 2 objects per page, the second page’s end_index() would return 4.
 96 
 97 Attributes 
 98 
 99 Page.object_list 
100 The list of objects on this page.
101 
102 Page.number 
103 The 1-based page number for this page.
104 
105 Page.paginator 
106 The associated Paginator object.
Django核心分页模块的文档一些类和方法

特征

使用与django.core.pagination相同的API,因此与现有代码完全兼容。
具有动态查询字符串创建,它考虑到现有的GET参数。
开箱即用的HTML呈现的分页
其他方法可以更容易地呈现更高级的分页模板。

安装

 1 Install package from PYPI:
 2 
 3 pip install django-pure-pagination
 4 or clone and install from repository:
 5 
 6 git clone git@github.com:jamespacileo/django-pure-pagination.git
 7 cd django-pure-pagination
 8 python setup.py install
 9 Add pure_pagination to INSTALLED_APPS
10 
11 INSTALLED_APPS = (
12     ...
13     'pure_pagination',
14 )
15 Finally substitute from django.core.paginator import Paginator with from pure_pagination import Paginator

设置

1 A few settings can be set within settings.py
2 
3 PAGINATION_SETTINGS = {
4     'PAGE_RANGE_DISPLAYED': 10,
5     'MARGIN_PAGES_DISPLAYED': 2,
6     'SHOW_FIRST_PAGE_WHEN_INVALID': True,
7 }

PAGE_RANGE_DISPLAYED is the number of pages neighbouring the current page which will be displayed (default is 10)

MARGIN_PAGES_DISPLAYED is the number of pages neighbouring the first and last page which will be displayed (default is 2)

Set SHOW_FIRST_PAGE_WHEN_INVALID to True when you want to just show first page when provided invalid page instead of 404 error

http://i.imgur.com/LCqrt.gif

 

例子1:(参考官方例子)

# views.py
from django.shortcuts import render_to_response

from pure_pagination import Paginator, EmptyPage, PageNotAnInteger


def index(request):

    try:
        page = request.GET.get('page', 1)
    except PageNotAnInteger:
        page = 1

    objects = ['john', 'edward', 'josh', 'frank']

    # Provide Paginator with the request object for complete querystring generation

    p = Paginator(objects,per_page=2,request=request)

    people = p.page(page)

    return render_to_response('index.html', {
        'people': people,
    }
template file: index.html
{% for person in people.object_list %}
<div>
First name: {{ person }}
</div>
{% endfor %}
{# The following renders the pagination html #}
<div id="pagination">
{{ people.render }}
</div>

例子2:

试图文件
views.py
from django.shortcuts import render_to_response from pure_pagination import Paginator, EmptyPage, PageNotAnInteger def page(request): # 文章列表 article_list = list(range(443)) # 分页数据 try: page = int(request.GET.get('page', 1)) # 页码 paginator = Paginator(article_list, 20, request=request) # 获取有多少页 article_list = paginator.page(page) # 获取指定页的数据 except Exception as e: page = 1 return render(request, 'page.html', { 'page_obj': article_list })
分页模板文件
_pagination.html

{% load i18n %}
<div class="pagination">
    {% if page_obj.has_previous %}
        <a href="?{{ page_obj.previous_page_number.querystring }}" class="prev">{% trans "上一页" %}</a>
    {% else %}
        <span class="disabled prev">{% trans "上一页" %}</span>
    {% endif %}
    {% for page in page_obj.pages %}
        {% if page %}
            {% ifequal page page_obj.number %}
                <span class="current page">{{ page }}</span>
            {% else %}
                <a href="?{{ page.querystring }}" class="page">{{ page }}</a>
            {% endifequal %}
        {% else %}
            ...
        {% endif %}
    {% endfor %}
    {% if page_obj.has_next %}
        <a href="?{{ page_obj.next_page_number.querystring }}" class="next">{% trans "下一页" %}</a>
    {% else %}
        <span class="disabled next">{% trans "下一页" %}</span>
    {% endif %}
</div>
page.html
{% for page in page_obj.object_list %} <div>{{ page }}<br /></div> {% endfor %} {% include "_pagination.html" %}
注:views返回的对象的名字page_obj要和page.html和_pagination.html中相对应的对象名一直。

 结果:(对官方的添加了一些样式)

 1     <style>
 2         a{
 3             text-decoration: none;
 4         }
 5         .pagination .page{
 6             display: inline-block;
 7             width: 33px;
 8             height: 33px;
 9             border: 1px solid #e1e2e3;
10             line-height: 33px;
11             text-align: center;
12             cursor: pointer;
13         }
14         .pagination .prev, .next{
15             display: inline-block;
16             width: 68px;
17             height: 33px;
18             border: 1px solid #e1e2e3;
19             line-height: 33px;
20             text-align: center;
21         }
22 
23         span.current.page{
24             background-color: #f7f7f7;
25         }
26     </style>

posted @ 2017-11-14 14:16  Maclean  阅读(212)  评论(0)    收藏  举报