django中分页器的使用方法(初、高级版本)

效果图:


方法如下:

1.简单版(较繁琐但是直观):

1.1 定义数据库模型(models.py)中添加表

class ProductSample(models.Model):
    # 示例商品表
    id = models.AutoField(db_column='ID', primary_key=True)  # Field name made lowercase.
    item_id = models.CharField(verbose_name="用户ID",max_length=255, blank=True, null=True)
    title = models.TextField(verbose_name="标题",blank=True, null=True)
    pict_url = models.CharField(verbose_name="商品图片链接",max_length=255, blank=True, null=True)
    category = models.TextField(verbose_name="类别",blank=True, null=True)
    brand_id = models.CharField(verbose_name="品牌ID",max_length=255, blank=True, null=True)
    seller_id = models.CharField(verbose_name="卖家ID",max_length=255, blank=True, null=True)

    def __str__(self):
        return self.title

    # class Meta:
    #     verbose_name = '商品信息'
    #     verbose_name_plural = verbose_name
    class Meta:
        managed = False
        db_table = 'product_sample'

1.2 路由(urls.py)中添加路径

path("home/", views.home,name='home'), #主页面

1.3 在视图中(view.py)添加如下代码

from .models import ProductSample #导入表
from django.utils.safestring import mark_safe

"""
需要修改如下代码(替换为自己的表):
#数据总条数
total_count = 替换.objects.all().order_by('id').count()
#MySQL上获取数据
documents = 替换.objects.all().order_by('id')[start:end]  # 指定按 id 字段排序
"""
def home(request):
    """主页面"""
    # 分页器设计
    page = int(request.GET.get('page',1))
    size = 10    #每页显示10条
    start = (page - 1)*size
    end = page*size
    #数据总条数
    total_count = ProductSample.objects.all().order_by('id').count()
    #总页码
    total_page_count, div = divmod(total_count, size)
    if div:
        total_page_count +=1

    #MySQL上获取数据
    documents = ProductSample.objects.all().order_by('id')[start:end]  # 指定按 id 字段排序


    #计算初当前页的前五页和后五页
    plus = 5
    if total_page_count <= 2 * plus + 1:
        #数据库中的数据较少,没有达到11页
        start_page = 1
        end_page = total_page_count
    else:
        #数据库中的数据较多 大于11页

        #当前页<5时
        if page <= plus:
            start_page = 1
            end_page = 2 * plus
        else:
            #当前页>5
            #当前页+5总页码
            if (page + plus ) > total_page_count:
                start_page = total_page_count - 2 * plus
                end_page = total_page_count
            else:
                start_page = page - plus
                end_page = page + plus
    #页码
    page_str_list = []

    #首页
    page_str_list.append('<li><a href ="?page={}">首页</a></li>'.format(1))

    #上一页
    if page > 1:
        prev = '<li><a href ="?page={}" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>'.format(page-1)
    else:
        prev = '<li><a href ="?page={}" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>'.format(1)
    page_str_list.append(prev)
    #页面
    for i in range(start_page,end_page+1):
        if i== page:
            ele = '<li class="active"><a href ="?page={}">{}</a></li>'.format(i,i)
        else:
            ele = '<li><a href ="?page={}">{}</a></li>'.format(i,i)
        page_str_list.append(ele)

    #下一页
    if page < total_page_count:
        next_page = '<li><a href ="?page={}" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>'.format(page+1)
    else:
        next_page = '<li><a href ="?page={}" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>'.format(total_page_count)
    page_str_list.append(next_page)

    #尾页
    page_str_list.append('<li><a href ="?page={}">尾页</a></li>'.format(total_page_count))
    #搜索
    search_string ="""
    <li>
            <form style="display: inline-block;" method="get">
                <div class="input-group" style="width: 200px;display: inline-block;">
                    <input name="page"
                           style="position: relative;float: left;display: inline-block;width: 80px;border-radius: 0;"
                           type="text" class="form-control" placeholder="页码">
                    <span class="input-group-btn">
            <button style="border-radius: 0;" class="btn btn-default" type="submit">跳转</button>
        </span>
                </div>
            </form>
    </li>
    """
    page_str_list.append(search_string)

    page_string = mark_safe("".join(page_str_list))
    return render(request,'home/home.html',locals())

1.4 html页面使用分页器

<div>
{% for d in documents %}
{{ d.pict_url }}
{{ d.title }}
<p>价格:${{ random_num }}</p>
{% endfor %}

  <nav aria-label="Page navigation">
     <ul class="pagination">
         {{ page_string }}
      </ul>
  </nav>
</div>
{% endblock %}

2 高级版(设置组件,可用于其他数据的分页)

2.1 自定义分页组件(在app里面新建一个utils目录,在utils里面新建一个pagination.py文件)将下面代码添加到pagination.py文件中,使用说明如下:

缺点:搜索+分页器时,不能将搜索的情况保留(下面有改进版,按需设计)

"""
自定义的分页组件,以后想要使用这个分页组件,需要做如下几件事:

#在视图函数中:
from home.utils.pagination import Pagination

def home(request):
    # 1.根据自己的情况去筛选自己的数据
    queryset = ProductSample.objects.all()
    # 2.实例化分页对象
    page_object = Pagination(request,queryset)
    page_queryset = page_object.page_queryset  #分页后的数据
    page_string = page_object.html()  #页码

    return render(request,'home/home.html',locals())
    
#在HTML页面中:
    {% for d in page_queryset %}
        <h4> {{ d.title }} </h4>
    {% endfor %}

    <ul class="pagination">
        {{ page_string }}
    </ul>
"""

from django.utils.safestring import mark_safe
class Pagination(object):

    def __init__(self,request,queryset,size = 10, plus=5, page_param="page"):
        """
        :param request: 请求的对象
        :param queryset: 符合条件的数据(对该数据进行分页处理)
        :param size:每页显示多少条数据
        :param plus:显示当前页的前或后几页(页码)
        :param page_param:在URL中传递的获取分页的参数,例如:/home/?page=12
        """
        page = request.GET.get(page_param, "1")
        if page.isdecimal():
            page = int(page)
        else:
            page = 1
        self.page = page
        self.size = size  # 每页显示10条
        self.start = (page - 1) * size
        self.end = page * size
        self.page_queryset =queryset[self.start:self.end]

        # 数据总条数
        total_count = queryset.count()
        # 总页码
        total_page_count, div = divmod(total_count, size)
        if div:
            total_page_count += 1
        self.total_page_count = total_page_count
        self.plus = plus

    def html(self):
        # 计算初当前页的前五页和后五页
        if self.total_page_count <= 2 * self.plus + 1:
            # 数据库中的数据较少,没有达到11页
            start_page = 1
            end_page = self.total_page_count
        else:
            # 数据库中的数据较多 大于11页

            # 当前页<5时
            if self.page <= self.plus:
                start_page = 1
                end_page = 2 * self.plus
            else:
                # 当前页>5
                # 当前页+5总页码
                if (self.page + self.plus) > self.total_page_count:
                    start_page = self.total_page_count - 2 * self.plus
                    end_page = self.total_page_count
                else:
                    start_page = self.page - self.plus
                    end_page = self.page + self.plus
        # 页码
        page_str_list = []

        # 首页
        page_str_list.append('<li><a href ="?page={}">首页</a></li>'.format(1))

        # 上一页
        if self.page > 1:
            prev = '<li><a href ="/home/?page={}" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>'.format(
                self.page - 1)
        else:
            prev = '<li><a href ="?page={}" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>'.format(
                1)
        page_str_list.append(prev)
        # 页面
        for i in range(start_page, end_page + 1):
            if i == self.page:
                ele = '<li class="active"><a href ="?page={}">{}</a></li>'.format(i, i)
            else:
                ele = '<li><a href ="?page={}">{}</a></li>'.format(i, i)
            page_str_list.append(ele)

        # 下一页
        if self.page < self.total_page_count:
            next_page = '<li><a href ="?page={}" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>'.format(
                self.page + 1)
        else:
            next_page = '<li><a href ="?page={}" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>'.format(
                self.total_page_count)
        page_str_list.append(next_page)

        # 尾页
        page_str_list.append('<li><a href ="?page={}">尾页</a></li>'.format(self.total_page_count))
        # 搜索
        search_string = """
            <li>
                    <form style="display: inline-block;" method="get">
                        <div class="input-group" style="width: 200px;display: inline-block;">
                            <input name="page"
                                   style="position: relative;float: left;display: inline-block;width: 80px;border-radius: 0;"
                                   type="text" class="form-control" placeholder="页码">
                            <span class="input-group-btn">
                    <button style="border-radius: 0;" class="btn btn-default" type="submit">跳转</button>
                </span>
                        </div>
                    </form>
            </li>
            """
        page_str_list.append(search_string)
        page_string = mark_safe("".join(page_str_list))
        return page_string

3 高级版的升级(搜索+分页)

修改pagination.py文件。原理:保留参数
问题:跳转不能实现搜索的跳转,处理办法,结合Ajax来实现。

"""
自定义的分页组件,以后想要使用这个分页组件,需要做如下几件事:

在视图函数中:
from home.utils.pagination import Pagination

def home(request):

    # 1.根据自己的情况去筛选自己的数据
    queryset = ProductSample.objects.all()
    # 2.实例化分页对象
    page_object = Pagination(request,queryset)
    page_queryset = page_object.page_queryset  #分页后的数据
    page_string = page_object.html()  #页码

    return render(request,'home/home.html',locals())
    
    #在HTML页面中:
    {% for d in page_queryset %}
        <h4> {{ d.title }} </h4>
    {% endfor %}

    <ul class="pagination">
        {{ page_string }}
    </ul>
"""

from django.utils.safestring import mark_safe
class Pagination(object):

    def __init__(self,request,queryset,size = 10, plus=5, page_param="page"):
        """
        :param request: 请求的对象
        :param queryset: 符合条件的数据(对该数据进行分页处理)
        :param size:每页显示多少条数据
        :param plus:显示当前页的前或后几页(页码)
        :param page_param:在URL中传递的获取分页的参数,例如:/home/?page=12
        """

        from  django.http.request import QueryDict
        import copy
        query_dict = copy.deepcopy(request.GET)
        query_dict._mutable = True
        self.query_dict = query_dict
        self.page_param = page_param


        page = request.GET.get(page_param, "1")
        if page.isdecimal():
            page = int(page)
        else:
            page = 1
        self.page = page
        self.size = size  # 每页显示10条
        self.start = (page - 1) * size
        self.end = page * size
        self.page_queryset =queryset[self.start:self.end]

        # 数据总条数
        total_count = queryset.count()
        # 总页码
        total_page_count, div = divmod(total_count, size)
        if div:
            total_page_count += 1
        self.total_page_count = total_page_count
        self.plus = plus

    def html(self):
        # 计算初当前页的前五页和后五页
        if self.total_page_count <= 2 * self.plus + 1:
            # 数据库中的数据较少,没有达到11页
            start_page = 1
            end_page = self.total_page_count
        else:
            # 数据库中的数据较多 大于11页

            # 当前页<5时
            if self.page <= self.plus:
                start_page = 1
                end_page = 2 * self.plus
            else:
                # 当前页>5
                # 当前页+5总页码
                if (self.page + self.plus) > self.total_page_count:
                    start_page = self.total_page_count - 2 * self.plus
                    end_page = self.total_page_count
                else:
                    start_page = self.page - self.plus
                    end_page = self.page + self.plus
        # 页码
        page_str_list = []

        self.query_dict.setlist(self.page_param,[1])
        # 首页
        page_str_list.append('<li><a href ="?{}">首页</a></li>'.format(self.query_dict.urlencode()))

        # 上一页
        if self.page > 1:
            self.query_dict.setlist(self.page_param, [self.page - 1])
            prev = '<li><a href ="?{}" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>'.format(
                self.query_dict.urlencode())
        else:
            self.query_dict.setlist(self.page_param, [1])
            prev = '<li><a href ="?{}" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>'.format(
                self.query_dict.urlencode())
        page_str_list.append(prev)
        # 页面
        for i in range(start_page, end_page + 1):
            if i == self.page:
                self.query_dict.setlist(self.page_param, [i])
                ele = '<li class="active"><a href ="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i)
            else:
                self.query_dict.setlist(self.page_param, [i])
                ele = '<li><a href ="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i)
            page_str_list.append(ele)

        # 下一页
        if self.page < self.total_page_count:
            self.query_dict.setlist(self.page_param, [self.page + 1])
            next_page = '<li><a href ="?{}" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>'.format(
                self.query_dict.urlencode())
        else:
            self.query_dict.setlist(self.page_param, [self.total_page_count])
            next_page = '<li><a href ="?{}" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>'.format(
                self.query_dict.urlencode())
        page_str_list.append(next_page)

        # 尾页
        self.query_dict.setlist(self.page_param, [self.total_page_count])
        page_str_list.append('<li><a href ="?{}">尾页</a></li>'.format(self.query_dict.urlencode()))
        # 搜索
        search_string = """
            <li>
                    <form style="display: inline-block;" method="get">
                        <div class="input-group" style="width: 200px;display: inline-block;">
                            <input name="page"
                                   style="position: relative;float: left;display: inline-block;width: 80px;border-radius: 0;"
                                   type="text" class="form-control" placeholder="页码">
                            <span class="input-group-btn">
                    <button style="border-radius: 0;" class="btn btn-default" type="submit">跳转</button>
                </span>
                        </div>
                    </form>
            </li>
            """
        page_str_list.append(search_string)
        page_string = mark_safe("".join(page_str_list))
        return page_string

热门相关:逼婚首席:影后前妻很抢手   亿万老公,送上门!   重生豪门宠婚:枭宠不乖娇妻   绝宠小医妃:王爷,来一针   极品仙医在都市