Django 分页功能比较强大,这边是结合官网的内容写的可以参考
https://docs.djangoproject.com/en/1.9/topics/pagination/
>>> from django.core.paginator import Paginator >>>
objects = [ 'john' , 'paul' , 'george' , 'ringo' ] >>>
p = Paginator(objects, 2 ) >>>
p.count 4 >>>
p.num_pages 2 >>> type (p.page_range) #
`<type 'rangeiterator'>` in Python 2. < class 'range_iterator' > >>>
p.page_range range ( 1 , 3 ) >>>
page1 = p.page( 1 ) >>>
page1 <Page 1 of 2 > >>>
page1.object_list [ 'john' , 'paul' ] >>>
page2 = p.page( 2 ) >>>
page2.object_list [ 'george' , 'ringo' ] >>>
page2.has_next() False >>>
page2.has_previous() True >>>
page2.has_other_pages() True >>>
page2.next_page_number() Traceback
(most recent call last): ... EmptyPage:
That page contains no results >>>
page2.previous_page_number() 1 >>>
page2.start_index() #
The 1-based index of the first item on this page 3 >>>
page2.end_index() #
The 1-based index of the last item on this page 4 >>>
p.page( 0 ) Traceback
(most recent call last): ... EmptyPage:
That page number is less
than 1 >>>
p.page( 3 ) Traceback
(most recent call last): ... EmptyPage:
That page contains no results |
views
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
from django.core.paginator import Paginator,
EmptyPage, PageNotAnInteger from django.shortcuts import render def listing(request): contact_list = Contacts.objects. all () paginator = Paginator(contact_list, 25 ) #
Show 25 contacts per page page = request.GET.get( 'page' ) try : contacts = paginator.page(page) except PageNotAnInteger: #
If page is not an integer, deliver first page. contacts = paginator.page( 1 ) except EmptyPage: #
If page is out of range (e.g. 9999), deliver last page of results. contacts = paginator.page(paginator.num_pages) return render(request, 'list.html' ,
{ 'contacts' :
contacts}) |
网页html 代码编写
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
{%
for contact in contacts %} {#
Each "contact" is a Contact model object. #} {{
contact.full_name|upper }}< br /> ... {%
endfor %} < div class="pagination"> < span class="step-links"> {%
if contacts.has_previous %} < a href="?page={{
contacts.previous_page_number }}">previous</ a > {%
endif %} < span class="current"> Page
{{ contacts.number }} of {{ contacts.paginator.num_pages }}. </ span > {%
if contacts.has_next %} < a href="?page={{
contacts.next_page_number }}">next</ a > {%
endif %} </ span > </ div > |