Django Component


1620 浏览 5 years, 7 months

6 pagination

版权声明: 转载请注明出处 http://www.codingsoho.com/

使用pagination库

1.安装

pip install django-pagination

2.修改setting.py文件

INSTALLED_APPS = [
    # **
    'pagination',
]

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

3.导入tag

在要进行列表分页的页面(template)的页面上方(最好是最上面)中 导入它的tag

{% load pagination_tags %}

4.模板更新

在你的模板(template)页面上,对你想要分页的列表变量(object_list)进行分页,在模板中写如下代码:(这段短代码的位置要在 放在 你显示 object_list 之前)

{% autopaginate object_list %}

上面对列表分页后默认每页有20个,如果你想自己自定义,可以这样:

{% autopaginate object_list 10 %}

这样对列表分页后每页显示10个。

结束处添加

{% paginate %}

Django 1.9适配

pagination库并没有一直更新,到了django1.9上就不能直接支持了,大概的修改如下

1) AttributeError: 'WSGIRequest' object has no attribute 'REQUEST'

搜索找到 middleware.py 文件(我的在python2.7\Lib\site-packages\pagination),

修改REQUESTGET.get

return int(self.REQUEST['page'])

新代码如下

return int(self.GET.get('page'))

2)TypeError: sequence index must be integer, not 'slice'

搜索找到 pagination_tags.py (我的在 python2.7\Lib\site-packages\pagination\templatetags),

first = set(page_range[:window])
last = set(page_range[-window:])

current = set(page_range[current_start:current_end])

新代码如下

first = set(list(page_range)[:window])
last = set(list(page_range)[-window:])

current = set(list(page_range)[current_start:current_end])

Django 1.10 适配

运行时会报错

Traceback (most recent call last):
  File "..\env\Lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "..\env\Lib\site-packages\django\core\management\commands\runserver.py", line 142, in inner_run
    handler = self.get_handler(*args, **options)
  File "..\env\Lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler
    handler = super(Command, self).get_handler(*args, **options)
  File "..\env\Lib\site-packages\django\core\management\commands\runserver.py", line 64, in get_handler
    return get_internal_wsgi_application()
  File "..\env\Lib\site-packages\django\core\servers\basehttp.py", line 46, in get_internal_wsgi_application
    return get_wsgi_application()
  File "..\env\Lib\site-packages\django\core\wsgi.py", line 14, in get_wsgi_application
    return WSGIHandler()
  File "..\env\Lib\site-packages\django\core\handlers\wsgi.py", line 153, in __init__
    self.load_middleware()
  File "..\env\Lib\site-packages\django\core\handlers\base.py", line 82, in load_middleware
    mw_instance = middleware(handler)
TypeError: object() takes no parameters

主要原因是:Django1.10 引入了一种新的中间件,可以使用 MiddlewareMixin 进行兼容。

try:
    from django.utils.deprecation import MiddlewareMixin
except ImportError:
    MiddlewareMixin = object

class PaginationMiddleware(MiddlewareMixin):
    def process_request(self, request):
        request.__class__.page = property(get_page)

有的时候也可以通过调整middleware顺序来解决,不知道规律,所以不推荐

参考文档