django 分页

django 提供自己封装的分页控件,可供使用
下面示例

models.py

1
2
3
4
5
6
7
8
9
from django.db import models

class UserInfo(models.Model):
username = models.CharField(max_length=128, null=True, blank=True)
name = models.CharField(max_length=128, null=True, blank=True)
password = models.CharField(max_length=128, null=True, blank=True)

def __str__(self):
return self.username

urls.py

1
2
3
4
5
6
7
8
from django.conf.urls import url
from django.contrib import admin
from demo01 import views

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^test/', views.Test),
]

/demo01/views.py

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
from django.shortcuts import render

from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger


from demo01 import models
# Create your views here.

def Test(request):
data_obj_li = models.UserInfo.objects.all()
p = Paginator(data_obj_li, 2) #每一页显示几条

print("数据总数", p.count)
print("数据页数", p.num_pages)
print("数据页数范围", p.page_range)
print("是否有下一页", p.page(2).has_next())
print("是否有上一页", p.page(2).has_previous())
print("是否有其他页码", p.page(2).has_other_pages())
print("下一页的页码", p.page(2).next_page_number())
print("上一页的页码", p.page(2).previous_page_number())

get_page = int(request.GET.get('page', 1))

try:
data_obj_li = p.page(get_page)
except PageNotAnInteger:
data_obj_li = p.page(1)
except EmptyPage:
data_obj_li = p.page(p.num_pages)

return render(request, 'test.html', locals())

templates/test.html

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table>
<thread>
<tr>
<th>用户名</th>
<th>密码</th>
<th>人名</th>
</tr>
</thread>
<tbody>
{% for item in data_obj_li %}
<tr>
<td>{{ item.username }}</td>
<td>{{ item.password }}</td>
<td>{{ item.name }}</td>
</tr>

{% endfor %}
</tbody>
</table>

<div>
<ul class="paginator" id ="page">
{% if data_obj_li.has_previous %}
<li class="previous"><a href="/test/?page="{{ data_obj_li.previous_page_number }}>上一页</a></li>
{% else %}
<li class="previous disabled"><a href="#">上一页</a></li>
{% endif %}

{% for num in p.page_range %}
{% if num == get_page %}
<li class="item active"><a href="/test/?page= {{ num }}">{{ num }}</a></li>
{% else %}
<li class="item"><a href="/test/?page={{ num }}">{{ num }}</a></li>
{% endif %}
{% endfor %}


{% if data_obj_li.has_next %}
<li class="next"><a href="/test/?page={{ data_obj_li.next_page_number }}">下一页</a></li>
{% else %}
<li class="next disabled"><a href="#">下一页</a></li>
{% endif %}

</ul>
</div>
</body>
</html>

Recommended Posts