Django分页是比较方便的,我们可以使用内置的一个paginator类。
这里以查询图书为例,以下是主要代码:
---------------------------------------------------------------------------------------------------
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
views.py
#导入方法PageNotAnInteger, Paginator, InvalidPage, EmptyPage
from
django.core.paginator
import
PageNotAnInteger, Paginator, InvalidPage, EmptyPage
def
list
(request):
books
=
Book.objects.
all
()
#之前需要从models中导入Book
after_range_num
=
5
#当前页前显示5页
befor_range_num
=
4
#当前页后显示4页
try
:
#如果请求的页码少于1或者类型错误,则跳转到第1页
page
=
int
(request.GET.get(
"page"
,
1
))
if
page <
1
:
page
=
1
except
ValueError:
page
=
1
paginator
=
Paginator(books,
2
)
# 设置books在每页显示的数量,这里为2
try
:
#跳转到请求页面,如果该页不存在或者超过则跳转到尾页
books_list
=
paginator.page(page)
except
(EmptyPage,InvalidPage,PageNotAnInteger):
books_list
=
paginator.page(paginator.num_pages)
if
page >
=
after_range_num:
page_range
=
paginator.page_range[page
-
after_range_num:page
+
befor_range_num]
else
:
page_range
=
paginator.page_range[
0
:
int
(page)
+
befor_range_num]
return
render
-
to_response(
'book_list.html'
,{
'books'
:books_list,
'page_range'
:page_range})
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Templates 视图
book_list.html
{
%
for
book
in
books.object_list
%
}
{{ book.
id
}} | {{ book.name }} <br
/
>
{
%
endfor
%
}
<div>
{
%
if
books.has_previous
%
}
<a href
=
"?page={{ books.previous_page_number }}"
>< 上一页<
/
a>
{
%
endif
%
}
<span>
{
%
for
p
in
page_range
%
}
{
%
ifequal p books.number
%
}
<span
class
=
"current"
>{{p}}<
/
span>
{
%
else
%
}
<a href
=
"?page={{p}}"
title
=
"第{{p}}页"
>{{p}}<
/
a>
{
%
endifequal
%
}
{
%
endfor
%
}
<
/
span>
{
%
if
books.has_next
%
}
<a href
=
"?page={{ books.next_page_number }}"
>下一页 > <
/
a>
{
%
endif
%
}
<a >[第{{ books.number }}
/
{{ books.paginator.num_pages }}页]<
/
a>
<
/
div>
|