Django-自定义分页

封装好的自定义分页器

class Page():

    def __init__(self, page_num, total_count, base_url, params, per_page=10, max_page=11):

        """
        page_num: 当前页码数
        total_count: 数据总数
        base_url: a标签href的前缀
        params: request对象,是QueryDict类型
        per_page: 每页显示多少条数据
        max_page: 单一页面上最多显示几个页码
        """

        self.page_num = page_num
        self.total_count = total_count
        self.base_url = base_url
        self.params = params
        self.per_page = per_page
        self.max_page = max_page

        # 总页码
        total_page, m = divmod(self.total_count, self.per_page)
        if m:
            total_page += 1
        self.total_page = total_page

        try:
            self.page_num = int(self.page_num)
            # 如果输入的页码数大于最大的页码数,默认返回第一页
            if self.page_num > self.total_page:
                self.page_num = self.total_page
            elif self.page_num <= 0:
                self.page_num = 1
        except Exception as e:
            # 当输入的页码不是数字时,返回第一页
            self.page_num = 1

        # 定义两个变量保存数据从哪取到哪
        self.data_start = (self.page_num - 1) * 10
        self.data_end = self.page_num * 10

        #页面上总共展示多少页码
        #如果总页数小于设定的单页显示页码数
        if self.total_page < self.max_page:
            self.max_page = self.total_page
        # 让选定页码取中,计算左右两边长度
        self.half_max_page = self.max_page // 2

        # 页面上展示的页码从哪开始
        self.page_start = self.page_num - self.half_max_page
        # 页面上展示的页码从哪结束
        self.page_end = self.page_num + self.half_max_page
        # 如果开始页数小于1
        if self.page_start <= 1:
            self.page_start = 1
            self.page_end = self.max_page
        # 如果结束页面大于最大页码数
        elif self.page_end >= self.total_page:
            self.page_start = self.total_page - self.max_page + 1
            self.page_end = self.total_page

        #拷贝一份request对象,是个QueryDict形式,后面会用于获取及修改url
        import copy
        self.params = copy.deepcopy(self.params) #{"page":"12","title_startwith":"py","id_gt":"5"}

    @property
    def start(self):
        return self.data_start

    @property
    def end(self):
        return self.data_end

    def page_html(self):

        # 自己拼接分页的HTML代码
        html_str_list = []
        # 加上上一页标签
        #判断一下如果是第一页就没有上一页了
        if self.page_num <= 1:
            html_str_list.append('<li class="disabled"><a href="#"><span aria-hidden="true">«</span></a></li>')
        #否则加上上一页
        else:
            self.params["page"] = self.page_num - 1
            html_str_list.append('<li><a href="{0}?{1}"><span aria-hidden="true">«</span></a></li>'.format(self.base_url ,self.params.urlencode()))

        # 加上首页
        self.params["page"] = 1
        html_str_list.append('<li><a href="{0}?{1}">首页</a></li>'.format(self.base_url, self.params.urlencode()))

        for i in range(self.page_start, self.page_end + 1):
            #把QueryDict中的page修改为当前循环的页码
            self.params["page"] = i
            # 如果i等于当前页就加一个样式类
            if i == self.page_num:
                tmp = '<li class="active"><a href="{0}?page={1}">{2}</a></li>'.format(self.base_url, self.params.urlencode(), i)
            else:
                tmp = '<li><a href="{0}?{1}">{2}</a></li>'.format(self.base_url, self.params.urlencode(), i)
            html_str_list.append(tmp)

        # 加上尾页
        self.params["page"] = self.total_page
        html_str_list.append('<li><a href="{0}?{1}">尾页</a></li>'.format(self.base_url, self.params.urlencode()))

        # 加上下一页标签
        #判断,如果是最后一页,就没有下一页
        if self.page_num >= self.total_page:
            html_str_list.append('<li class="disabled"><a href="#"><span aria-hidden="true">»</span></a></li>')
        else:
            self.params["page"] = self.page_num + 1
            html_str_list.append('<li><a href="{0}?{1}"><span aria-hidden="true">»</span></a></li>'.format(self.base_url, self.params.urlencode()))

        page_html = "".join(html_str_list)

        return page_html

使用指南

def books(request):
    #从url取当前页数
    page_num = request.GET.get("page", 1)
    #总数据量
    total_count = models.Book.objects.all().count()
    #获取当前访问url
    base_url = request.path
    #引入分页器并实例化一个对象
    from utils.mypage import Page
    page_obj = Page(page_num, total_count, base_url, request.GET, per_page=10, max_page=9)

    ret = models.Book.objects.all()[page_obj.start:page_obj.end]

    page_html = page_obj.page_html()

    return render(request, "books.html", {"books": ret, "page_html": page_html})
相关文章
相关标签/搜索