7.3.列表分页

django-pure-pagination

用法:https://github.com/jamespacileo/django-pure-pagination

安装

安装django-pure-pagination

pip install django-pure-pagination

在INSTALLED_APPS中添加 pure_pagination

INSTALLED_APPS = (
    ...
    'pure_pagination',
)

最后,使用from pure_pagination import Paginator替换 from django.core.paginator import Paginator

设置

A few settings can be set within settings.py

PAGINATION_SETTINGS = {
    'PAGE_RANGE_DISPLAYED': 10,
    'MARGIN_PAGES_DISPLAYED': 2,

    'SHOW_FIRST_PAGE_WHEN_INVALID': True,
}

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

Usage example

Following is a simple example for function based views. For generic class-based views, see bellow.

view file: views.py

# views.py
from django.shortcuts import render_to_response

from pure_pagination import Paginator, EmptyPage, PageNotAnInteger

def index(request):

    objects = ['john', 'edward', 'josh', 'frank']
    try:
        page = request.GET.get('page', 1)
    except PageNotAnInteger:
        page = 1
    p = Paginator(objects, 5, request=request)
    people = p.page(page)
    return render_to_response('index.html', {
        'people': people,
    }

Usage

There a few different way you can make use of the features introduced within django-pure-pagination.

Easiest way to render the pagination is to call the render method i.e.

Alternatively you can access the Page object low level methods yourself

Special note: page_obj and current_page both point to the page object within the template.

{% load i18n %}
<div class="pagination">
    {% if page_obj.has_previous %}
        <a href="?{{ page_obj.previous_page_number.querystring }}" class="prev">&lsaquo;&lsaquo; {% trans "previous" %}</a>
    {% else %}
        <span class="disabled prev">&lsaquo;&lsaquo; {% trans "previous" %}</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 "next" %} &rsaquo;&rsaquo;</a>
    {% else %}
        <span class="disabled next">{% trans "next" %} &rsaquo;&rsaquo;</span>
    {% endif %}
</div>

Last updated

Was this helpful?