# mypage.py
import copy from django.core.paginator import * from django.utils.safestring import mark_safe class PAGE(object): def __init__(self): self.request = None self.querysets = None self.page_range = None def view_page(self,request,querysets): self.request = request page = request.GET.get('_page', 1) try: p = Paginator(querysets, 3) querysets = p.page(page) except PageNotAnInteger: querysets = p.page(1) except EmptyPage: querysets = p.page(p.num_pages) self.querysets = querysets page_range = [i for i in range(int(page) - 2, int(page) + 3) if 0 < i <= p.num_pages] self.page_range = page_range return querysets def html_page(self): request_GET = copy.deepcopy(self.request.GET) code = '<ul class="pagination">' try: if self.querysets.has_previous(): request_GET['_page'] = self.querysets.previous_page_number() code += '<li class="long"><a href="?%s">上一页</a></li>'% request_GET.urlencode() for page in self.page_range: request_GET['_page'] = page if page > 0: if page == self.querysets.number: code += '<li class="active"><a href="?%s">%s</a></li>'%(request_GET.urlencode(),page) else: code += '<li><a href="?%s"class="page">%s</a></li>'%(request_GET.urlencode(),page) if self.querysets.has_next(): request_GET['_page'] = self.querysets.next_page_number() code += '<li class="long"><a href="?%s">下一页</a></li>'% request_GET.urlencode() except Exception as e: print(e) code += '</ul>' return mark_safe(code) ppp = PAGE()
视图函数中:
#分页
from .mypage import ppp querysets = ppp.view_page(request,querysets) #注意:querysets变量名 和 括号内参数名一致,如左 htm = ppp.html_page()
模版中:
{{ htm }}
问题:有警告 UnorderedObjectListWarning,是因为传入分页组件中的对象queryset无序
解决:在模型的Meta中添加默认排序 ordering = ('-pk',)