• day56 自定义分页器


    ajax结合sweetalert实现删除按钮动态效果

    如果ajax进行前后端交互,通常后端返回给ajax一个字典

    下载sweetalert

    使用SweetAlert for Bootstrap

    <body>
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <h1 class="text-center">数据展示</h1>
                <br>
                <table class="table table-hover table-bordered table-striped">
                    <thead>
                    <tr>
                        <th>序号</th>
                        <th>用户名</th>
                        <th>年龄</th>
                        <th>性别</th>
                        <th class="text-center">操作</th>
                    </tr>
                    </thead>
                    <tbody>
                        {% for user_obj in user_queryset %}
                            <tr>
                                <td>{{ forloop.counter }}</td>
                                <td>{{ user_obj.username }}</td>
                                <td>{{ user_obj.age }}</td>
                                <td>{{ user_obj.get_gender_display }}</td>
                                <td class="text-center">
                                    <a href="#" class="btn btn-primary btn-sm">编辑</a>
                                    <a href="#" class="btn btn-primary btn-sm cancle" userid="{{ user_obj.pk }}">删除</a>
                                </td>
                            </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <script>
        $('.cancle').click(function () {
            var $btn=$(this)
           swal({
              title: "确定删除吗?",
              text: "如果删除了,就无法恢复数据了!",
              type: "warning",
              showCancelButton: true,
              confirmButtonClass: "btn-danger",
              confirmButtonText: "确定删除!",
              cancelButtonText: "算了,取消删除!",
              closeOnConfirm: false,
              closeOnCancel: false,
               showLoaderOnConfirm: true
            },
            function(isConfirm) {
              if (isConfirm) {
                  $.ajax({
                      url:'',
                      type:'post',
                      data:{'delete_id':$btn.attr('userid')},
                      success:function (data) {
                          if(data.code==1000){
                              swal("已经删除了!",data.msg, "success");
                              $btn.parent().parent().remove()
                          }else {
                              swal("有bug!",'发生未知的错误', "warning");
                          }
                      }
                  })
              } else {
                swal("谨言慎行", "牛逼啊", "error");
              }
            });
        })
    </script>
    </body>
    
    from django.http import JsonResponse
    def home(request):
        if request.is_ajax():
            back_dic={'code':1000,'msg':''}
            delete_id=request.POST.get('delete_id')
            time.sleep(3)
            models.User.objects.filter(pk=delete_id).delete()
            back_dic['msg']='数据已经删除了'
            return JsonResponse(back_dic)
        user_queryset=models.User.objects.all()
        return render(request,'home.html',locals())
    
    

    bulk_create批量插入数据

    <body>
    {% for book_obj in book_queryset %}
        <p>{{ book_obj.title }}</p>
    {% endfor %}
    </body>
    
    def index(request):
        book_list=[]
        for i in range(1000):
            book_list.append(models.Book(title=f'第{i}本书'))
        #批量插入数据,建议使用bulk_cteate方法
        models.Book.objects.bulk_create(book_list)
        book_queryset=models.Book.objects.all()
        return render(request,'index.html',locals())
    

    自定义分页器

    推导

    book_queryset = models.Book.objects.all()
        # 一页展示的条数
        per_page_num = 10
        all_count=book_queryset.count()
        all_page_num,more=divmod(all_count,per_page_num)
        if more:
            all_page_num+=1#需要多少也面展示
        #用户想要查看的页码
        current_page=request.GET.get('page',1)
        current_page=int(current_page)
        start_page=(current_page-1)*per_page_num
        end_page=current_page*per_page_num
        html=''
        xxx=current_page
        if current_page<6:
            xxx=6
    
        for i in range(xxx-5,xxx+6):
            if current_page==i:
                html+='<li class="active"><a href="?page=%s">%s</a></li>'%(i,i)
            else:
                html+='<li><a href="?page=%s">%s</a></li>'%(i,i)
        book_queryset=book_queryset[start_page:end_page]
        return  render(request,'index.html',locals())
    
    <div class="container">
        <div class="col-md-offset-2 col-md-8">
            {% for book_obj in book_queryset %}
                <p>{{ book_obj }}</p>
            {% endfor %}
            <nav aria-label="Page navigation">
                <ul class="pagination">
                    <li>
                        <a href="#" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    {{ html|safe }}
                    <li>
                        <a href="#" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
    </div>
    

    自定义

    1.在应用下创建一个目录(utils),在目录下创建一个py文件。

    class Pagination(object):
        def __init__(self, current_page, all_count, per_page_num=2, pager_count=11):
            """
            封装分页相关数据
            :param current_page: 当前页
            :param all_count:    数据库中的数据总条数
            :param per_page_num: 每页显示的数据条数
            :param pager_count:  最多显示的页码个数
    
            用法:
            queryset = model.objects.all()
            page_obj = Pagination(current_page,all_count)
            page_data = queryset[page_obj.start:page_obj.end]
            获取数据用page_data而不再使用原始的queryset
            获取前端分页样式用page_obj.page_html
            """
            try:
                current_page = int(current_page)
            except Exception as e:
                current_page = 1
    
            if current_page < 1:
                current_page = 1
    
            self.current_page = current_page
    
            self.all_count = all_count
            self.per_page_num = per_page_num
    
            # 总页码
            all_pager, tmp = divmod(all_count, per_page_num)
            if tmp:
                all_pager += 1
            self.all_pager = all_pager
    
            self.pager_count = pager_count
            self.pager_count_half = int((pager_count - 1) / 2)
    
        @property
        def start(self):
            return (self.current_page - 1) * self.per_page_num
    
        @property
        def end(self):
            return self.current_page * self.per_page_num
    
        def page_html(self):
            # 如果总页码 < 11个:
            if self.all_pager <= self.pager_count:
                pager_start = 1
                pager_end = self.all_pager + 1
            # 总页码  > 11
            else:
                # 当前页如果<=页面上最多显示11/2个页码
                if self.current_page <= self.pager_count_half:
                    pager_start = 1
                    pager_end = self.pager_count + 1
    
                # 当前页大于5
                else:
                    # 页码翻到最后
                    if (self.current_page + self.pager_count_half) > self.all_pager:
                        pager_end = self.all_pager + 1
                        pager_start = self.all_pager - self.pager_count + 1
                    else:
                        pager_start = self.current_page - self.pager_count_half
                        pager_end = self.current_page + self.pager_count_half + 1
    
            page_html_list = []
            # 添加前面的nav和ul标签
            page_html_list.append('''
                        <nav aria-label='Page navigation>'
                        <ul class='pagination'>
                    ''')
            first_page = '<li><a href="?page=%s">首页</a></li>' % (1)
            page_html_list.append(first_page)
    
            if self.current_page <= 1:
                prev_page = '<li class="disabled"><a href="#">上一页</a></li>'
            else:
                prev_page = '<li><a href="?page=%s">上一页</a></li>' % (self.current_page - 1,)
    
            page_html_list.append(prev_page)
    
            for i in range(pager_start, pager_end):
                if i == self.current_page:
                    temp = '<li class="active"><a href="?page=%s">%s</a></li>' % (i, i,)
                else:
                    temp = '<li><a href="?page=%s">%s</a></li>' % (i, i,)
                page_html_list.append(temp)
    
            if self.current_page >= self.all_pager:
                next_page = '<li class="disabled"><a href="#">下一页</a></li>'
            else:
                next_page = '<li><a href="?page=%s">下一页</a></li>' % (self.current_page + 1,)
            page_html_list.append(next_page)
    
            last_page = '<li><a href="?page=%s">尾页</a></li>' % (self.all_pager,)
            page_html_list.append(last_page)
            # 尾部添加标签
            page_html_list.append('''
                                               </nav>
                                               </ul>
                                           ''')
            return ''.join(page_html_list)
    

    导入上面写的py文件

    from app01.utils.mypage import Pagination
    def index(request):
        #自定义分页器的使用
        book_queryset = models.Book.objects.all()
        # 用户想要查看的页码
        current_page = request.GET.get('page', 1)
        all_count=book_queryset.count()
        page_obj=Pagination(current_page=current_page,all_count=all_count,per_page_num=10,pager_count=5)
        page_queryset=book_queryset[page_obj.start:page_obj.end]# book_queryset = book_queryset[start_page:end_page]
        return render(request,'index.html',locals())
    
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                {% for book in page_queryset %}  <!--将页面上原本的queryset数据全部换成切片之后的queryset即可-->
                    <p>{{ book }}</p>
                {% endfor %}
                {{ page_obj.page_html|safe }}
            </div>
        </div>
    </div>
    

    多对多三种创建方式

    forms组件

    cookie与session操作

    django中间件

    跨站请求伪造csrf

    auth模块

    bbs小作业

  • 相关阅读:
    侯捷STL课程及源码剖析学习1
    路边拾遗之其他模块(struct/csv/xlwt/smtp)
    面向对象之内置方法(简单)、组合。以及接口归一化设计与抽象类
    面向对象之继承与派生
    面向对象之类属性实例属性及其增删改查
    python中常用模块详解二
    函数之命名空间、作用域、闭包、装饰器四剑客。
    文件操作之1,2,3
    python中常用模块详解一
    python内置常用内置方法详解
  • 原文地址:https://www.cnblogs.com/zqfzqf/p/11973741.html
Copyright © 2020-2023  润新知