本文实例讲述了Django框架实现的简单分页功能。分享给大家供大家参考,具体如下:
前面一篇《Django开发的简易留言板》写了个简单的留言板,如果数据量太多的话在一页显示就不那么友好了,本文就是做一个分页显示。
代码在上一篇的基础上修改。
导入分页模块并修改views
1
2
3
4
5
6
7
8
9
|
#只需修改index函数即可 from django.core.paginator import Paginator def index(request): messages = models.Message.objects. all () #获取全部数据 limit = 10 paginator = Paginator(messages, limit) #按每页10条分页 page = request.GET.get( 'page' , '1' ) #默认跳转到第一页 result = paginator.page(page) return render(request, 'guestbook/index.html' , { 'messages' : result}) |
修改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
55
56
|
<!DOCTYPE html> < html > < head > < meta charset = "utf-8" /> < title >留言板</ title > < link rel = "stylesheet" href = "https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel = "external nofollow" crossorigin = "anonymous" > </ head > < body > < table class = "table table-striped table-bordered table-hover table-condensed" > < thead > < tr class = "danger" > < th >留言时间</ th > < th >留言者</ th > < th >标题</ th > < th >内容</ th > </ tr > </ thead > < tbody > {% if messages %} {% for message in messages %} < tr class = "{% cycle 'active' 'success' 'warning' 'info' %}" > < td >{{ message.publish|date:'Y-m-d H:i:s' }}</ td > < td >{{ message.username }}</ td > < td >{{ message.title }}</ td > < td >{{ message.content }}</ td > </ tr > {% endfor %} {% else %} < tr > < td colspan = "4" >无数据</ td > </ tr > {% endif %} </ tbody > </ table > <!-- 分页开始 --> < div > < ul class = "pagination" > < li >< a href = "/guestbook/index/?page=1" rel = "external nofollow" >首页</ a ></ li > {% if messages.has_previous %} < li >< a href = "/guestbook/index/?page={{ messages.previous_page_number }}" rel = "external nofollow" >上一页</ a ></ li > {% endif %} {% for num in messages.paginator.page_range %} < li >< a href = "/guestbook/index/?page={{ num }}" rel = "external nofollow" >{{ num }}</ a ></ li > {% endfor %} {% if messages.has_next %} < li >< a href = "/guestbook/index/?page={{ messages.next_page_number }}" rel = "external nofollow" >下一页</ a ></ li > {% endif %} < li >< a href = "/guestbook/index/?page={{ messages.paginator.num_pages }}" rel = "external nofollow" >尾页</ a ></ li > </ ul > </ div > <!-- 分页结束 --> < div > < a class = "btn btn-xs btn-primary" href = "/guestbook/create/" rel = "external nofollow" >去留言</ a > </ div > </ body > </ html > |
其实主要使用了Django自带的Paginator模块,关于这个模块大家可以自己去官方文档查看,功能还是挺强大的,如果配合ListView的话,三行代码就可以实现分页功能。
希望本文所述对大家基于Django框架的Python程序设计有所帮助。
原文链接:https://blog.csdn.net/Yort2016/article/details/73551274