2022暑期实践(Django教程学习记录)(第三周1)P44靓号管理-分页组件封装

本文介绍了一个Django应用中实现分页和搜索功能的代码示例。通过`Pagination`类处理请求的GET参数,实现了动态分页,并在`pretty_list`视图中结合搜索功能展示靓号列表。页面使用了自动生成的HTML页码结构,提供首页、上一页、下一页、尾页链接以及当前页码的高亮显示。同时,提供了跳转到任意页码的功能。
摘要由CSDN通过智能技术生成

P44靓号管理-分页组件封装

要解决的问题,分页和搜索功能不能同时用

    from django.http.request import QueryDict
    import copy
    query_dict = copy.deepcopy(request.GET)
    query_dict._mutable = True
    query_dict.setlist('page', [11])
    print(query_dict.urlencode())
class Pagination(object):
    def __init__(self, request, queryset, page_size=10, page_param="page", plus=5):
        page = request.GET.get(page_param, "1")
        print(page, type(page))
        if page.isdecimal():
            page = int(page)
        else:
            page = 1
        print(page, type(page))
        self.page = page
        self.page_size = page_size
        self.start = (page-1)*page_size
        self.end = page * page_size
        self.page_queryset = queryset[self.start:self.end]

        total_count = queryset.count()
        total_page_count, div = divmod(total_count, page_size)
        if div:
            total_page_count += 1
        self.total_page_count = total_page_count
        self.plus = plus

    # 封装自动生成前端内容
    def html(self):
        # 数据库中的数据比较少,没有达到11页:
        if self.total_page_count <= (2*self.plus+1):
            start_page = self.page - self.plus
            end_page = self.page + self.plus
        # 数据库中的数据比较多,>11页
        else:
            # 往前翻页小于等于plus=5
            if self.page <= self.plus:
                start_page = 1
                end_page = 2 * self.plus + 1
            # 往后翻页码,当前页码+5>总页面
            elif 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


        # queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")[start:end]
        # select * from 表 order by level asc;
        # models.PrettyNum.objects.all().order_by("level")

        # 生成前端页码
        from django.utils.safestring import mark_safe
        page_str_list = []
        # 首页
        first_page = '<li><a href="?page=1">首页</a></li>'
        page_str_list.append(first_page)
        # 上一页:
        if self.page > 1:
            prev_page = '<li><a href="?page={}">上一页</a></li>'.format(self.page-1)
        else:
            prev_page = '<li><a href="?page={}">上一页</a></li>'.format(1)
        page_str_list.append(prev_page)
        # for i in range(1, total_page_count+1):
        for i in range(start_page, end_page):
            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={}">下一页</a></li>'.format(self.page + 1)
        else:
            next_page = '<li><a href="?page={}">上一页</a></li>'.format(self.total_page_count)
        page_str_list.append(next_page)
        # 尾页
        last_page = '<li><a href="?page={}">尾页</a></li>'.format(self.total_page_count)
        page_str_list.append(last_page)

        page_string = "".join(page_str_list)
        page_string = mark_safe(page_string)

        return page_string

def pretty_list(request):
# P44,组件分页,测试代码
    """靓号列表"""
    # select * from 表 order by level desc;
    data_dict = {}
    search_data = request.GET.get('q', '')
    if search_data:
        data_dict['mobile__contains'] = search_data

    from app03_phone_number_management.utils.pagination import Pagination
    queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")
    page_object = Pagination(request, queryset)
    page_queryset = page_object.page_queryset
    page_string = page_object.html()

    context = {
        'queryset': page_queryset,
        'search_data': search_data,  # 分完页的数据
        "page_string": page_string,  # 分页功能模块
    }
    return render(request, 'pretty_list.html', context)

{% extends 'layout.html' %}

{% block content %}
    <div class="container">
        <div style="margin-bottom: 10px" class="clearfix">
            <a class="btn btn-success" href="/pretty_add/" target="_blank">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
                新建靓号
            </a>
            <div style="float: right; width: 300px;">
                {#                <input type="text" placeholder="搜索靓号" name="q">#}
                <form action="/pretty_list/" method="GET">
                    <div class="input-group">
                        <input type="text" class="form-control" placeholder="搜索靓号" name="q" value="{{ search_data }}">
                        <span class="input-group-btn">
                            <button class="btn btn-default" type="submit">
                                <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
                            </button>
                        </span>
                    </div><!-- /input-group -->
                </form>
            </div>
        </div>
        <div class="panel panel-default">
            <div class="panel-heading">
                <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
                用户列表
            </div>
            <div class="panel-body">
                <table class="table">
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>号码</th>
                        <th>价格</th>
                        <th>级别</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>

                    {% for obj in queryset %}
                        <tr>
                            <th>{{ obj.id }}</th>
                            <th>{{ obj.mobile }}</th>
                            <th>{{ obj.price }}</th>
                            <th>{{ obj.get_level_display }}</th>
                            <th>{{ obj.get_status_display }}</th>
                            <td>
                                <a href="/pretty_edit/{{ obj.id }}/" class="btn btn-primary btn-xs">编辑</a>
                                <a href="/pretty_del/{{ obj.id }}/" class="btn btn-danger btn-xs">删除</a>
                            </td>
                        </tr>
                    {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
        <nav aria-label="...">
            <ul class="pagination">
                {#        <li class="disabled"><a href="#" aria-label="Previous"><span aria-hidden="true">«</span></a></li>#}
                {#        <li><a href="?page=1">1 <span class="sr-only">(current)</span></a></li>#}
                {#        <li><a href="?page=2">2</a></li>#}
                {#        <li><a href="?page=3">3</a></li>#}
                {#        <li><a href="?page=4">4</a></li>#}
                {#        <li><a href="?page=5">5</a></li>#}
                {#        <li><a href="#" aria-label="Next"><span aria-hidden="true">»</span></a></li>#}
                {{ page_string }}
            </ul>
            <br/>
            <form method="GET">
                <div class="input-group" style="width: 200px">
                    <input type="text" name="page" class="form-control" placeholder="页码">
                    <span class="input-group-btn">
                        <button class="btn btn-default" type="submit">跳转</button>
                    </span>
                </div>
            </form>
        </nav>
    </div>

{% endblock %}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值