Django中实现自动分页 2014-10-30 11:00

基本介绍

  • 安装

安装方法1:

1
2
3
4
5
6
7
wget --no-check-certificate \
       https://pypi.python.org/packages/source/d/\
       django-pagination/django-pagination-1.0.7.tar.gz\
       #md5=43353a0b3344e5b10a9a83248a6dc24a
     tar -zxvf django-pagination-1.0.7.tar.gz
    cd django-pagination-1.0.7 
    python setup.py install

安装方法2:

1
2
pip install django-pagination
easy_install django-pagination
  • 配置 settings.py:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
INSTALLED_APPS = (
       # ...
       'pagination',
   )

MIDDLEWARE_CLASSES = (
       # ...
       'pagination.middleware.PaginationMiddleware',
   )

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    "django.core.context_processors.request"  # new add
)
  • 使用:

template最上方:

{% load pagination_tags %}

template遍历object_list前:

{% autopaginate object_list 30 %}

尾部增加导航:

{% paginate %}
  • 定制导航样式:

修改文件./lib/python2.6/site-packages/django_pagination-1.0.7-py2.6.egg/pagination/templates/pagination/pagination.html

改为:

{% if is_paginated %}
{% load i18n %}
<div class="pagination" style="vertical-align:middle; text-align:center;margin: 0px 0px 0px;">
<ul>
    {% if page_obj.has_previous %}
        <li><a href="?page={{ page_obj.previous_page_number }}{{ getvars }}{{ hashtag }}" class="prev">‹‹ {% trans "previous" %}</a></li>
    {% else %}
        <li class="disabled"><a href="#">‹‹ {% trans "previous" %}</a></li>
    {% endif %}
    {% for page in pages %}
        {% if page %}
            {% ifequal page page_obj.number %}
                <li class="active"><a href="#">{{ page }}</a></li>
            {% else %}
                <li><a href="?page={{ page }}{{ getvars }}{{ hashtag }}" class="page">{{ page }}</a></li>
            {% endifequal %}
        {% else %}
            <li><span class="page">...</span></li>
        {% endif %}
    {% endfor %}
    {% if page_obj.has_next %}
        <li><a href="?page={{ page_obj.next_page_number }}{{ getvars }}{{ hashtag }}" class="next">{% trans "next" %} ››</a></li>
    {% else %}
        <li class="disabled"><a href="#">{% trans "next" %} ››</a></li>
    {% endif %}
</ul>
</div>
{% endif %}
  • 定制样式方法2

在项目中创建如下文件:templates/pagination/pagination.html

如果不成果,还需要做如下操作:

后在view的html文件中,将:

{% paginate %}

改为:

{% paginate using "pagination/pagination.html" %}
Tags: #Django    Post on Python