django實現分頁功能
阿新 • • 發佈:2018-11-06
在個人部落格或者網站上,我們發表文章經常會對部落格進行分頁,下面程式碼用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 %}