django 分页功能
一、安装django-prue-pagination
在pycharm中 File==》settings==》Project:项目名===》Project Interpreter==》点击“+”===》搜django-prue-pagination===》左下角Intall Package
二、在sttings.py中的相关代码:
..... #注册pure_pagination INSTALLED_APPS = [ ....... 'pure_pagination', ] ...... #追加pure_pagination配置代码 PAGINATION_SETTINGS={ 'PAGE_RANGE_DISPLAYED':10, 'MARGIN_PAGES_DISPLAYED':2, 'SHOW_FIRST_PAGE_WHEN_INVALID':True, }
三、在views.py中添加分页代码:
...... from .models import ShopProfile ...... from pure_pagination import Paginator,EmptyPage,PageNotAnInteger ...... class ShopList(View): """商铺列表""" def get(self,request): shops=ShopProfile.objects.all() # 每页五个 p = Paginator(shops, 5) page = request.GET.get('page', 1) try: shops= p.page(int(page)) except PageNotAnInteger: shops=p.page(1) return render(request,'shops_list.html',{'all_shops':shops})
四、在shop-list.html中的代码:
...... <!--收到后台分页后 返回的数据,然后进行遍历--> <div id="portfoliolist"> {% for shop in all_shops.object_list %} <!--关键代码,一定注意这里!要遍历的不是all_shops而是all_object_list,这里是一个巨坑!不然会报错:
'Page' object is not iterable--> <div class="portfolio shop" data-cat="shop"> <div class="portfolio-wrapper"> <img src="{% static 'logo/shop.jpg' %}" alt="" /> <div class="label"> <div class="label-text"><a class="text-title">{{ shop.name }}</a><span class="text-category">{{ shop.shop_sn }}</span></div> <div class="label-bg"></div> </div> </div> </div> {% endfor %} </div> <!--分页的代码--> <div class="fen-page"> <ul class="pagelist pagination"> {% if all_shops.has_previous %} <li class="long"> <a href="?{{ all_shops.previous_page_number.querystring }}" class="prev">上一页</a> </li> {% endif %} {% for page in all_shops.pages %} {% if page %} {% ifequal page all_shops.number %} <li class="active"> <a href="?{{ page.querystring }}">{{ page }}</a> </li> {% else %} <li> <a href="?{{ page.querystring }}" class="page">{{ page }}</a> </li> {% endifequal %} {% else %} <li class="none"><a href="">...</a></li> {% endif %} {% endfor %} {% if all_shops.has_next %} <li class="long"> <a href="?{{ all_shops.next_page_number.querystring }}">下一页</a> </li> {% endif %} </ul> </div>