from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def listing(request): OBJECTS_TO_SHOW = ['test%d' % x for x in xrange(10)] NUM_PER_PAGE = 4 paginator = Paginator(OBEJCTS_TO_SHOW, NUM_PER_PAGE) page = request.GET.get('page') try: contents = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. contents = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. contents = paginator.page(paginator.num_pages)
{% for content in contents %} {{ content }}<br /> ... {% endfor %} <div class="pagination"> <span class="step-links"> {% if contacts.has_previous %} <a href="?page={{ contents.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ contacts.number }} of {{ contents.paginator.num_pages }}. </span> {% if contents.has_next %} <a href="?page={{ contents.next_page_number }}">next</a> {% endif %} </span> </div>
Paginator 實例具備的屬性方法django
Paginator.page(page_num) # 返回第page_num頁的一個Page實例 Paginator.count # 全部要顯示的內容的長度 Paginator.num_pages # 全部要顯示的內容分紅的頁碼數,即共多少頁 Paginator.page_range # 頁碼範圍
Page 實例具備的屬性/方法spa
Page.previous() Page.next() Page.has_other_pages() Page.previous_page_number() Page.next_page_number() Page.start_index() Page.end_index() Page.object_list # 在本頁中顯示的內容 Page.number # 本頁頁碼 Page.paginator # 對應的Paginator實例