django实现分页功能

在个人博客或者网站上,我们发表文章经常会对博客进行分页,下面代码用django实现:

django有它自带的分页功能:Paginator

不过我们用在它基础上开发的另一个包:django-pure-pagination 

先了解一下这个包特性:

1、使用与django.core相同的API,因此与现有代码完全兼容。

2、它考虑了现有的GET参数,具有动态查询字符串创建。

3、用html呈现分页功能,开箱即用(方便)

4、使呈现更高级的分页模板更加容易。

使用:

一、安装

在虚拟环境中通过pip安装:

pip install django-pure-pagination

INSTALLED_APPS里添加pure-pagination

1 INSTALLED_APPS = (
2     ...
3     'pure_pagination',
4 )

二、设置

在setting.py中设置:

 1 INSTALLED_APPS = (
 2     ...
 3     'pure_pagination',
 4 )
 5 
 6 PAGINATION_SETTINGS = {
 7     'PAGE_RANGE_DISPLAYED': 3,    #中间显示的个数
 8     'MARGIN_PAGES_DISPLAYED': 2,  #两边显示的个数
 9 
10     'SHOW_FIRST_PAGE_WHEN_INVALID': True,
11 }

如图显示

用于展示底部分页栏中数量的显示,可以对其进行更改尝试不同效果。

3、视图函数(views.py)

 1 # views.py
 2 from django.shortcuts import render_to_response
 3 
 4 from pure_pagination import Paginator, EmptyPage, PageNotAnInteger
 5 
 6 
 7 def index(request):
 8 
 9     try:
10         page = request.GET.get('page', 1)
11     except PageNotAnInteger:
12         page = 1
13 
14     objects = ['john', 'edward', 'josh', 'frank']
15 
16     # Provide Paginator with the request object for complete querystring generation
17 
18     p = Paginator(objects, request=request)
19 
20     people = p.page(page)
21 
22     return render_to_response('index.html', {
23         'people': people,
24     }

4、前端展示  index.html

 1 {# index.html #}
 2 {% extends 'base.html' %}
 3 
 4 {% block content %}
 5 
 6 {% for person in people.object_list %}
 7     <div>
 8         First name: {{ person }}
 9     </div>
10 {% endfor %}
11 
12 {# The following renders the pagination html #}
13 <div id="pagination">
14     {{ people.render }}
15 </div>
16 
17 {% endblock %}

 

猜你喜欢

转载自www.cnblogs.com/zijue/p/9914550.html