系列文章将记录本人从零开始搭建资讯类的网站,所有源码都开放哦!欢迎互相讨论学习!
源码下载地址:https://github.com/wuqiwenpk/babyteach
本系列文章导航:https://github.com/wuqiwenpk/babyteach/blob/master/README.md
本篇目的
完成搜索页的数据分页展示(使用Django分页器Paginator)。
1、修改Views.py视图文件:
#搜索页视图 def search(request): qry = Detail.objects keyword = request.GET.get('keyword')#接收url搜索词关键字 pageindex = request.GET.get('p')#接收url页码 pagesize = 2 #自定义页容量 if keyword!='' and keyword is not None: print(keyword) list = qry.filter(title__contains=keyword) else: list = qry #分页 paginator = Paginator(list, pagesize)#使用Django的分页器 Paginator page = paginator.page(pageindex) print(page) return render(request, 'babyteach/search.html', {'list': page, 'keyword': keyword})
2、修改search.html模板html文件:
数据列表部分:
<p class="">关于 <font color="red">{{keyword}}</font> 的搜索,共 {{list.paginator.count}} 条检索结果:</p> <div class="list-unstyled mr-3"> {% for i in list %} <div class="media justify-content-center align-items-center align-middle border-bottom pt-4 pb-4"> <div class="media-body"> <h5 class="font-s18 font-weight-normal mb-2 lh-2"><a href="/detail/{{i.id}}" style="color:#252525;font-weight:;" target="_blank">{{i.title}}</a></h5> <p class="font-weight-light font-s14 text-gray mb-0">作者:{{i.author}} {{i.addtime | date:"Y-m-d H:i:s"}}</p> </div> </div> {%endfor%} </div>
分页器html部分:
<ul class="pagination justify-content-center mt-5 mb-5" id="pagenav"> <li class="page-item"><a class="page-link font-weight-light page_num page_num_1" href="/search?p=1&keyword={{keyword}}">首页</a></li> {% if list.has_previous %} <li class="page-item"><a class="page-link font-weight-light page_num page_num_1" href="/search?p={{list.previous_page_number}}&keyword={{keyword}}">上一页</a></li> <li class="page-item"><a class="page-link font-weight-light page_num page_num_1" href="/search?p={{list.previous_page_number}}&keyword={{keyword}}">{{list.previous_page_number}}</a></li> {% endif %} <li class="page-item active current"><a class="page-link font-weight-light" href="javascript:;">{{list.number}}</a></li> {% if list.has_next %} <li class="page-item"><a class="page-link font-weight-light page_num page_num_1" href="/search?p={{list.next_page_number}}&keyword={{keyword}}">{{list.next_page_number}}</a></li> <li class="page-item"><a class="page-link font-weight-light page_num page_num_1" href="/search?p={{list.next_page_number}}&keyword={{keyword}}">下一页</a></li> {% endif %} <li class="page-item"><a class="page-link font-weight-light page_num page_num_1" href="/search?p={{list.paginator.num_pages}}&keyword={{keyword}}">尾页</a></li> </ul>
3、运行测试:
数据:
访问测试:http://127.0.0.1:8002/search?p=1&keyword=11
本文总结:
完成搜索页的数据分页展示(使用Django分页器Paginator)。
完整源码地址:https://github.com/wuqiwenpk/babyteach