Django Paginator分页器的使用示例

# name: models.py
from django.db import models

class User(models.Model):
    id = models.AutoField(primary_key=True)
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)

# 插入测试数据
import random
def index(request):
    for i in range(1,100):
        chars = []
        pasd = []
        for x in range(1,8):
            chars.append(random.choice('abcdefghijklmnopqrstuvwxyz'))
            pasd.append(random.choice('0987654321'))
        user = "".join(chars)
        pwd = "".join(pasd)
        models.User.objects.create(username=user, password=pwd)
    return HttpResponse("ok")
<!--name: page.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >
</head>
<body>
<table class="table table-sm table-hover">
    <thead>
        <tr class="table-success">
            <th> 序号</th> <th> 用户名</th> <th> 用户密码</th>
        </tr>
    </thead>
    <tbody>
        {% for article in user_list %}
            <tr class="table-primary">
                <td>{{ article.id }}</td>
                <td>{{ article.username }}</td>
                <td>{{ article.password }}</td>
            </tr>
        {% endfor %}
    </tbody>
</table>
<nav class="d-flex justify-content-center" aria-label="Page navigation example">
    <ul class="pagination">
        <li class="page-item"><a class="page-link" href="./page?id=1" rel="external nofollow"  rel="external nofollow" >首页</a></li>
        {% if user_list.has_previous %}
            <li class="page-item"><a class="page-link" href="./page?id={{ user_list.previous_page_number }}" rel="external nofollow"  rel="external nofollow" >上一页</a></li>
        {% else %}
            <li class="page-item disabled"><a class="page-link" href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >上一页</a></li>
        {% endif %}

        {% for item in paginator.page_range %}
            {% if item == currentPage %}
                <li class="page-item active"><a class="page-link" href="./page?id={{ item }}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >{{ item }}</a></li>
            {% else %}
                <li class="page-item"><a class="page-link" href="./page?id={{ item }}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >{{ item }}</a></li>
            {% endif %}
        {% endfor %}

        {% if user_list.has_next %}
            <li class="page-item"><a class="page-link" href="./page?id={{ user_list.next_page_number }}" rel="external nofollow"  rel="external nofollow" >下一页</a></li>
        {% else %}
            <li class="page-item disabled"><a class="page-link" href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >下一页</a></li>
        {% endif %}
        <li class="page-item"><a class="page-link" href="./page?id={{ paginator.num_pages }}" rel="external nofollow"  rel="external nofollow" >尾页</a></li>
    </ul>
</nav>

<div style="text-align: center;" class="alert alert-dark">
   统计: {{ currentPage }}/{{ paginator.num_pages }} 共查询到:{{ paginator.count }} 条数据 页码列表:{{ paginator.page_range }}
</div>
</body>
</html>
# name: views.py
from django.shortcuts import render,HttpResponse
from MyWeb import models
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def page(request):
    user = models.User.objects.all()
    paginator = Paginator(user, 10)
    currentPage = int(request.GET.get("id",1))
    try:
        user_list = paginator.page(currentPage)
    except PageNotAnInteger:
        user_list = paginator.page(1)
    except:
        user_list = paginator.page(paginator.num_pages)

    return render(request,"page.html",{"user_list":user_list,
                                       "paginator":paginator,
                                       "currentPage":currentPage})
# name: urls.py
from MyWeb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('page',views.page)
]

上方的分页代码还有一个不足之处,当我们的页码数量过多时,会全部展示出来,整个页面都是很不美观,我们直接在上方代码上稍加修改一下试试.

# name: views.py
from django.shortcuts import render,HttpResponse
from MyWeb import models
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def page(request):
    user = models.User.objects.all()
    paginator = Paginator(user, 10)
    currentPage = int(request.GET.get("id",1))

    if paginator.num_pages > 15:
        if currentPage-5 < 1:
            pageRange = range(1,11)
        elif currentPage+5 > paginator.num_pages:
            pageRange = range(currentPage-5,paginator.num_pages)
        else:
            pageRange = range(currentPage-5,currentPage+5)
    else:
        pageRange = paginator.page_range

    try:
        user_list = paginator.page(currentPage)
    except PageNotAnInteger:
        user_list = paginator.page(1)
    except:
        user_list = paginator.page(paginator.num_pages)

    return render(request,"page.html",{"user_list":user_list,
                                       "paginator":paginator,
                                       "page_range":pageRange,        # 此处自定义一个分页段
                                       "currentPage":currentPage})

前端分页代码只需要将paginator.page_range改为page_range其他地方不需要动.

        {% for item in page_range %}
            {% if item == currentPage %}
                <li class="page-item active"><a class="page-link" href="./page?id={{ item }}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >{{ item }}</a></li>
            {% else %}
                <li class="page-item"><a class="page-link" href="./page?id={{ item }}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >{{ item }}</a></li>
            {% endif %}
        {% endfor %}

这样,无论有多少页面,都能够保证只显示10页。

分页后添加删除功能

1.删除功能的实现,很简单,只需要定位得到指定的tr上,取出里面的id号码,并发送给后端,执行sql删除就完事了。

<head>
    <meta charset="UTF-8">
    <title>Title</title>
     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>

<script type="text/javascript">
    $(document).ready(function(){
      $("#but1").click(function(){
            var obj = $("#tab");          // 定位到table表格
            var check = $("table input[type=checkbox]:checked");
            check.each(function(){        // 遍历节点
                var row = $(this).parent("td").parent("tr");  // 获取选中行
                var id = row.find("[name='uid']").html();     // 取出第一行的属性
                var name = row.find("[name='user']").html();
                alert("选中行的ID: " + id + "名字: " + name)
            });
      });
    });
</script>

<table id="tab" class="table table-sm table-hover">
    <thead>
        <tr class="table-success">
            <th>选择</th><th> 序号</th> <th> 用户名</th> <th> 用户密码</th>
        </tr>
    </thead>
    <tbody>
        {% for article in user_list %}
            <tr class="table-primary">
                <td> <input type="checkbox"></td>
                <td name="uid">{{ article.id }}</td>
                <td name="user">{{ article.username }}</td>
                <td>{{ article.password }}</td>
            </tr>
        {% endfor %}
    </tbody>
</table>
.................

<div>
    <button id="but1" class="btn btn-danger" onclick="check()">删除指定行</button>
</div>

实现模态框编辑内容

点击选中行,然后弹出模态框,并自动的获取到该行数据,编辑好以后直接用ajax发送post请求到后端处理即可。

<head>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>

<button type="button" id="but1" class="btn btn-success" data-toggle="modal" data-target="#staticBackdrop">弹框</button>

<script type="text/javascript">
    $(document).ready(function(){
      $("#but1").click(function(){
            var obj = $("#tab");
            var edit = $("table input[type=checkbox]:checked");
            edit.each(function(){
                var row = $(this).parent("td").parent("tr");
                var id = row.find("[name='uid']").html();
                var name = row.find("[name='user']").html();
                var email = row.find("[name='email']").html();
                $("#edit_id").val(id);
                $("#edit_name").val(name);
                $("#edit_email").val(email);
            });
      });
    });
</script>
<body>
<table id="tab" border="1" cellspacing="0">
    <thead>
        <tr>
            <th>选择</th><th>用户ID</th><th>用户名称</th><th>用户邮箱</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td> <input type="checkbox"></td>
            <td name="uid"> 1001</td>
            <td name="user"> lyshark</td>
            <td name="email"> lyshark@123.com</td>
        </tr>
        <tr>
            <td> <input type="checkbox"></td>
            <td name="uid"> 1002</td>
            <td name="user"> 搞事情</td>
            <td name="email"> lyshark@123.com</td>
        </tr>
    </tbody>
</table>

<div class="modal fade" id="staticBackdrop" data-backdrop="static" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="staticBackdropLabel">编辑模式</h5>
      </div>
      <div class="modal-body">
        <!--主体部分-->
        <div class="form-group row">
            <label class="col-sm-2 col-form-label">用户ID:</label>
            <div class="col-sm-10">
              <input type="text" id="edit_id" class="form-control">
            </div>

            <label class="col-sm-2 col-form-label">名称:</label>
            <div class="col-sm-10">
              <input type="text" id="edit_name" class="form-control">
            </div>

            <label class="col-sm-2 col-form-label">邮箱:</label>
            <div class="col-sm-10">
              <input type="text" id="edit_email" class="form-control">
            </div>
        </div>
      </div>

      <!--尾部内容-->
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary">提交数据</button>
      </div>
    </div>
  </div>
</body>

完整代码笔记

利用BootStrap框架实现分页: 通过使用bootstrap框架,并配合Django自带的分页组件即可实现简单的分页效果.

# name: models.py
from django.db import models

class User(models.Model):
    id = models.AutoField(primary_key=True)
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)

# 插入测试数据
import random
def index(request):
    for i in range(1,1000):
        chars = []
        pasd = []
        for x in range(1,8):
            chars.append(random.choice('abcdefghijklmnopqrstuvwxyz'))
            pasd.append(random.choice('0987654321'))
        user = "".join(chars)
        pwd = "".join(pasd)
        models.User.objects.create(username=user, password=pwd)
    return HttpResponse("ok")
<!--name: page.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >
</head>
<body>
<table class="table table-sm table-hover">
    <thead>
        <tr class="table-success">
            <th> 序号</th> <th> 用户名</th> <th> 用户密码</th>
        </tr>
    </thead>
    <tbody>
        {% for article in user_list %}
            <tr class="table-primary">
                <td>{{ article.id }}</td>
                <td>{{ article.username }}</td>
                <td>{{ article.password }}</td>
            </tr>
        {% endfor %}
    </tbody>
</table>
<nav class="d-flex justify-content-center" aria-label="Page navigation example">
    <ul class="pagination">
        <li class="page-item"><a class="page-link" href="./page?id=1" rel="external nofollow"  rel="external nofollow" >首页</a></li>
        {% if user_list.has_previous %}
            <li class="page-item"><a class="page-link" href="./page?id={{ user_list.previous_page_number }}" rel="external nofollow"  rel="external nofollow" >上一页</a></li>
        {% else %}
            <li class="page-item disabled"><a class="page-link" href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >上一页</a></li>
        {% endif %}

        {% for item in paginator.page_range %}
            {% if item == currentPage %}
                <li class="page-item active"><a class="page-link" href="./page?id={{ item }}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >{{ item }}</a></li>
            {% else %}
                <li class="page-item"><a class="page-link" href="./page?id={{ item }}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >{{ item }}</a></li>
            {% endif %}
        {% endfor %}

        {% if user_list.has_next %}
            <li class="page-item"><a class="page-link" href="./page?id={{ user_list.next_page_number }}" rel="external nofollow"  rel="external nofollow" >下一页</a></li>
        {% else %}
            <li class="page-item disabled"><a class="page-link" href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >下一页</a></li>
        {% endif %}
        <li class="page-item"><a class="page-link" href="./page?id={{ paginator.num_pages }}" rel="external nofollow"  rel="external nofollow" >尾页</a></li>
    </ul>
</nav>

<div style="text-align: center;" class="alert alert-dark">
   统计: {{ currentPage }}/{{ paginator.num_pages }} 共查询到:{{ paginator.count }} 条数据 页码列表:{{ paginator.page_range }}
</div>
</body>
</html>
# name: views.py
from django.shortcuts import render,HttpResponse
from MyWeb import models
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def page(request):
    user = models.User.objects.all()
    paginator = Paginator(user, 10)
    currentPage = int(request.GET.get("id",1))
    try:
        user_list = paginator.page(currentPage)
    except PageNotAnInteger:
        user_list = paginator.page(1)
    except:
        user_list = paginator.page(paginator.num_pages)

    return render(request,"page.html",{"user_list":user_list,
                                       "paginator":paginator,
                                       "currentPage":currentPage})
# name: urls.py
from MyWeb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('page',views.page)
]

上方的分页代码还有一个不足之处,当我们页面中的页码数量过多时,默认会将页码全部展示出来,整个页面看上去很不美观,我们可以直接在上方分页代码上稍加修改即可,如下代码.

# name: views.py
from django.shortcuts import render,HttpResponse
from MyWeb import models
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def page(request):
    user = models.User.objects.all()
    paginator = Paginator(user, 10)
    currentPage = int(request.GET.get("id",1))

    if paginator.num_pages > 15:
        if currentPage-5 < 1:
            pageRange = range(1,11)
        elif currentPage+5 > paginator.num_pages:
            pageRange = range(currentPage-5,paginator.num_pages)
        else:
            pageRange = range(currentPage-5,currentPage+5)
    else:
        pageRange = paginator.page_range

    try:
        user_list = paginator.page(currentPage)
    except PageNotAnInteger:
        user_list = paginator.page(1)
    except:
        user_list = paginator.page(paginator.num_pages)

    return render(request,"page.html",{"user_list":user_list,
                                       "paginator":paginator,
                                       "page_range":pageRange,        # 此处自定义一个分页段
                                       "currentPage":currentPage})

前端分页代码只需要将paginator.page_range改为page_range其他地方不需要动.

        {% for item in page_range %}
            {% if item == currentPage %}
                <li class="page-item active"><a class="page-link" href="./page?id={{ item }}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >{{ item }}</a></li>
            {% else %}
                <li class="page-item"><a class="page-link" href="./page?id={{ item }}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >{{ item }}</a></li>
            {% endif %}
        {% endfor %}

利用layui框架实现分页:

layui是一个完整的前端开发框架,利用它可以快速构建分页应用,比BootStrap更加灵活.

# models.py
from django.db import models

class HostDB(models.Model):
    id = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=64)
    hostaddr = models.CharField(max_length=64)
    hostmode = models.CharField(max_length=64)
<!--name: index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://lyshark.com/cdn/layui/css/layui.css" rel="external nofollow"  rel="external nofollow" >
    <script type="text/javascript" src="https://lyshark.com/cdn/layui/layui.js"></script>
</head>
<body>
<table class="layui-hide" id="demo"></table>

    <script type="text/javascript">
    layui.use('table', function(){
      var table = layui.table;
      table.render({
          elem: '#demo',
          url:'/get_page',
          method:'get',
          toolbar: '#toolbarDemo'         // 显示工具条
          ,request: {
                  pageName: 'pageIndex',  // 页码的参数名称,默认:page
                  limitName: 'pageSize'   // 每页数据量的参数名,默认:limit
          }
          ,response: {
                  statusName: 'code',     // 规定数据状态的字段名称,默认:code
                  statusCode: 0,          // 规定成功的状态码,默认:0
                  msgName: 'msg',         // 规定状态信息的字段名称,默认:msg
                  countName: 'DataCount', // 规定数据总数的字段名称,默认:count
                  dataName: 'data'        // 规定数据列表的字段名称,默认:data
          }
        ,cols: [[
          {type: 'checkbox', fixed: 'left'},
          {field:'id', title:'主机ID', width:100, sort: true},
          {field:'hostname', title:'主机名称', width:120},
          {field:'hostaddr', title:'主机地址', width:120},
          {field:'hostmode', title:'主机组', width:120},
        ]]
        ,page: {
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'],     // 自定义分页布局
            curr: 1,      // 设置默认起始页1
            groups: 10,   //只显示10个连续页码,就是说显示10个可见页其他的省略
            first: false, // 不显示首页
            last: false   // 不显示尾页
        },
        limit: 5,
        limits: [5,10,15,20,25]
      });
    });
    </script>
</body>
</html>
# views.py

from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from MyWeb import models
import json

def index(request):
    return render(request,"index.html")

def get_page(request):
    data = models.HostDB.objects.all()
    dataCount = data.count()
    pageIndex = request.GET.get("pageIndex")
    pageSize = request.GET.get("pageSize")
    print("当前索引:{} 当前大小:{}".format(pageIndex,pageSize))
    print("所有记录:{} 数据总条数:{}".format(data,dataCount))

    # 将数据组装成字典后放入data_list列表
    data_list,ref_data = [],[]
    for item in data:
        dict = { 'id':item.id , 'hostname':item.hostname, 'hostaddr':item.hostaddr, 'hostmode':item.hostmode }
        data_list.append(dict)

    # 使用分页器分页
    pageInator = Paginator(data_list,pageSize)
    context = pageInator.page(pageIndex)
    for item in context:
        ref_data.append(item)
    # 返回分页格式
    data = { "code": 0,"msg": "ok","DataCount": dataCount,"data": ref_data }
    return HttpResponse(json.dumps(data))
# name: url.py
from MyWeb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index),
    path('get_page/',views.get_page)
]

layui实现完整表格分页:

通过使用layui框架完成的一个相对完整的表格分页,可用于生产环境.

<!--name: index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://lyshark.com/cdn/layui/css/layui.css" rel="external nofollow"  rel="external nofollow" >
    <script type="text/javascript" src="https://lyshark.com/cdn/jquery/jquery3.js"></script>
    <script type="text/javascript" src="https://lyshark.com/cdn/layui/layui.js"></script>
</head>
<body>
<div class="demoTable">
    <div class="layui-inline">
        <input class="layui-input" name="id" id="demoReload" autocomplete="off">
    </div>
        <button class="layui-btn" data-type="reload">搜索</button>
</div>

<script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<table class="layui-hide" id="demo" lay-filter="test"></table>

    <script type="text/javascript">
    layui.use('table', function(){
      var table = layui.table;
      table.render({
          elem: '#demo',
          id: 'testReload',
          url:'/get_page',
          method:'get'
          ,request: {
                  pageName: 'pageIndex',  // 页码的参数名称,默认:page
                  limitName: 'pageSize'   // 每页数据量的参数名,默认:limit
          }
          ,response: {
                  statusName: 'code',     // 规定数据状态的字段名称,默认:code
                  statusCode: 0,          // 规定成功的状态码,默认:0
                  msgName: 'msg',         // 规定状态信息的字段名称,默认:msg
                  countName: 'DataCount', // 规定数据总数的字段名称,默认:count
                  dataName: 'data'        // 规定数据列表的字段名称,默认:data
          }
        ,cols: [[
          {type: 'checkbox', fixed: 'left'},
          {field:'id', title:'主机ID', width:100, sort: true},
          {field:'hostname', title:'主机名称', width:120},
          {field:'hostaddr', title:'主机地址', width:120},
          {field:'hostmode', title:'主机组', width:120},
          {fixed: 'right', title:'操作', toolbar: '#barDemo', width:120}
        ]]
        ,page: {
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'],     // 自定义分页布局
            curr: 1,      // 设置默认起始页1
            groups: 10,   // 只显示10个连续页码,就是说显示10个可见页其他的省略
            first: false, // 不显示首页
            last: false   // 不显示尾页
        },
        limit: 5,
        limits: [5,10,15,20,25]
      });
// ------------------------------------------------------------------
// 监听行工具事件:也就是编辑与删除的处理事件
      table.on('tool(test)', function(obj){
        var data = obj.data;
        if(obj.event === 'del'){
          layer.confirm('真的要删除本行数据吗 ?', {icon: 3,anim: 2}, function(index){
            // console.log("待删除ID: " + obj.data['id']);
           $.ajax({
               url:"/delete_page/",
               type:"get",
               data: {"id":obj.data['id']},
               success:function (recv) {
                   layer.msg("删除完成了..", {icon: 6});
               }
           });
            obj.del();
            layer.close(index);
          });
        } else if(obj.event === 'edit'){
          layer.prompt({ formType:2, title: "编辑表格",btn:['修改数据','关闭'],anim: 4,
              content:`<div>
                            主机序号: <input type="text" style='display:inline-block' id="id"><br><br>
                            主机名称: <input type="text" style='display:inline-block' id="hostname"><br><br>
                            主机地址: <input type="text" style='display:inline-block' id="hostaddr"><br><br>
                            主机属组: <input type="text" style='display:inline-block' id="hostmode"><br><br>
                       </div>`,
              yes:function (index,layero)
              {
                  console.log("点击yes触发事件:" + index);
                  var id = $("#id").val();
                  var hostname = $("#hostname").val();
                  var hostaddr = $("#hostaddr").val();
                  var hostmode = $("#hostmode").val();
                  $.ajax({
                      url: "/update_page",
                      type: "get",
                      data: {"id": id,
                              "hostname": hostname,
                              "hostaddr": hostaddr,
                              "hostmode": hostmode },
                      success:function (recv) {
                        // 修改完成后,本地直接更新数据,这样就无需刷新一次了
                          obj.update({
                              hostname: hostname,
                              hostaddr: hostaddr,
                              hostmode: hostmode
                          });
                          layer.msg("修改完成了..", {icon: 6});
                          layer.close(index);
                      }
                  });
              }
          });
              $("#id").val(data.id);
              $("#hostname").val(data.hostname);
              $("#hostaddr").val(data.hostaddr);
              $("#hostmode").val(data.hostmode);
        }
      });

        // 搜索后的重载,也就是找到数据以后直接更新
      var $ = layui.$, active = {
        reload: function(){
          var demoReload = $('#demoReload');
          //执行重载
          table.reload('testReload', {
            url:"/search_page",
            page: {
              curr: 1,
              limits: [1]
            }
            ,where: {
                hostname: demoReload.val()
            }
          });
        }
      };
    // ---------------------------------------------------------
    // 绑定搜索事件
      $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
          });
    });
    </script>
</body>
</html>
# name:views.py

from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from MyWeb import models
import json

def index(request):
    return render(request,"index.html")

def get_page(request):
    data = models.HostDB.objects.all()
    dataCount = data.count()
    pageIndex = request.GET.get("pageIndex")
    pageSize = request.GET.get("pageSize")
    print("当前索引:{} 当前大小:{}".format(pageIndex,pageSize))
    print("所有记录:{} 数据总条数:{}".format(data,dataCount))

    list = []
    res = []
    for item in data:
        dict = {}
        dict['id'] = item.id
        dict['hostname'] = item.hostname
        dict['hostaddr'] = item.hostaddr
        dict['hostmode'] = item.hostmode
        list.append(dict)

    pageInator = Paginator(list,pageSize)
    context = pageInator.page(pageIndex)
    for item in context:
        res.append(item)
    data = { "code": 0,"msg": "ok","DataCount": dataCount,"data": res }
    return HttpResponse(json.dumps(data))

def search_page(request):
    sql = request.GET.get("hostname")
    data = models.HostDB.objects.all().filter(hostname=sql)
    list = []
    for item in data:
        dict = {}
        dict['id'] = item.id
        dict['hostname'] = item.hostname
        dict['hostaddr'] = item.hostaddr
        dict['hostmode'] = item.hostmode
        list.append(dict)

    data = { "code": 0,"msg": "ok","DataCount": 1,"data": list }
    return HttpResponse(json.dumps(data))

def delete_page(request):
    get_id = request.GET.get("id")
    models.HostDB.objects.filter(id=get_id).delete()
    return render(request,"index.html")

def update_page(request):
    get_id = request.GET.get("id")
    get_hostname = request.GET.get("hostname")
    get_hostaddr = request.GET.get("hostaddr")
    get_hostmode = request.GET.get("hostmode")

    print(get_hostmode)
    obj = models.HostDB.objects.get(id=get_id)
    obj.hostname = get_hostname
    obj.hostaddr = get_hostaddr
    obj.hostmode = get_hostmode
    obj.save()
    return render(request,"index.html")
# name: urls.py

from MyWeb import views

urlpatterns = [
    path('',views.index),
    path('get_page/',views.get_page),
    path('search_page/',views.search_page),
    path('delete_page/',views.delete_page),
    path("update_page/",views.update_page)
]

自己实现分页:

转载代码,仅用于收藏。

from urllib.parse import urlencode

class Pagination(object):
    def __init__(self,current_page,total_count,base_url,params,per_page_count=10,max_pager_count=10):
        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.total_count = total_count

        # 每页显示10条数据
        self.per_page_count = per_page_count

        # 页面上应该显示的最大页码
        max_page_num, div = divmod(total_count, per_page_count)
        if div:
            max_page_num += 1
        self.max_page_num = max_page_num

        # 页面上默认显示11个页码(当前页在中间)
        self.max_pager_count = max_pager_count
        self.half_max_pager_count = int((max_pager_count - 1) / 2)

        # URL前缀
        self.base_url = base_url

        # request.GET
        import copy
        params = copy.deepcopy(params)
        # params._mutable = True
        get_dict = params.to_dict()
        # 包含当前列表页面所有的搜/索条件
        self.params = get_dict

    @property
    def start(self):
        return (self.current_page - 1) * self.per_page_count

    @property
    def end(self):
        return self.current_page * self.per_page_count

    def page_html(self):
        # 如果总页数 <= 11
        if self.max_page_num <= self.max_pager_count:
            pager_start = 1
            pager_end = self.max_page_num
        # 如果总页数 > 11
        else:
            # 如果当前页 <= 5
            if self.current_page <= self.half_max_pager_count:
                pager_start = 1
                pager_end = self.max_pager_count
            else:
                # 当前页 + 5 > 总页码
                if (self.current_page + self.half_max_pager_count) > self.max_page_num:
                    pager_end = self.max_page_num
                    pager_start = self.max_page_num - self.max_pager_count + 1   #倒这数11个
                else:
                    pager_start = self.current_page - self.half_max_pager_count
                    pager_end = self.current_page + self.half_max_pager_count

        page_html_list = []
        # {source:[2,], status:[2], gender:[2],consultant:[1],page:[1]}
        # 首页
        self.params['page'] = 1
        first_page = '首页' % (self.base_url,urlencode(self.params),)
        page_html_list.append(first_page)
        # 上一页
        self.params["page"] = self.current_page - 1
        if self.params["page"] <= 1:
            pervious_page = '上一页' % (self.base_url, urlencode(self.params))
        else:
            pervious_page = '上一页' % ( self.base_url, urlencode(self.params))
        page_html_list.append(pervious_page)
        # 中间页码
        for i in range(pager_start, pager_end + 1):
            self.params['page'] = i
            if i == self.current_page:
                temp = '%s' % (self.base_url,urlencode(self.params), i,)
            else:
                temp = '%s' % (self.base_url,urlencode(self.params), i,)
            page_html_list.append(temp)

        # 下一页
        self.params["page"] = self.current_page + 1
        if self.params["page"] > self.max_page_num:
            self.params["page"] = self.current_page
            next_page = '下一页' % (self.base_url, urlencode(self.params))
        else:
            next_page = '下一页' % (self.base_url, urlencode(self.params))
        page_html_list.append(next_page)

        # 尾页
        self.params['page'] = self.max_page_num
        last_page = '尾页' % (self.base_url, urlencode(self.params),)
        page_html_list.append(last_page)

        return ''.join(page_html_list)

文章出处:https://www.cnblogs.com/lyshark

以上就是Django Paginator分页器的使用示例的详细内容,更多关于Django Paginator分页器的使用的资料请关注我们其它相关文章!

(0)

相关推荐

  • Django 自定义分页器的实现代码

    为什么要实现分页? 在大部分网站中分页的功能都是必要的,尤其是在后台管理中分页更是不可或缺 分页能带给用户更好的体验,也能减轻服务器的压力 对于分页来说,有许多方法都可以实现 例如把数据全部读取出来在前端用javascript实现,但这样一次请求全部数据服务器压力很大, 还有就是在后端实现,每一次请求部分数据显示 分页需求: 1. 每页显示的多少条数据 2. 页面显示多少个页码 3. 上一页和下一页 4. 首页和尾页 效果演示: 代码实现: 分页类封装: 在我的app下创建一个page.py文件

  • Django的分页器实例(paginator)

    先导入模块: from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger 分页器paginator 下面的所有方法: book_list=Book.objects.all() paginator = Paginator(book_list, 10) #实例化出一个对象 print("count:",paginator.count) #数据总数 print("num_pages",p

  • django的分页器Paginator 从django中导入类

    先创建表,然后生成批量数据. 在models文件里 from django.db import models # Create your models here. class Book(models.Model): name = models.CharField(max_length=32) price = models.DecimalField(max_digits=5,decimal_places=2) 然后执行python manage.py makemigrations ,python

  • Django1.11自带分页器paginator的使用方法

    本文实例为大家分享了Django1.11自带分页器Django的具体使用方法,供大家参考,具体内容如下 接下来我编写一个 views ,名classify. classify,将模拟请求购物网站的分类产品.并分页返回数据.完成如下任务: 1.接受两个参数,type,page."type":为请求的购物网站产品类别,如 0代表热门.1代表 家居< 2.分类找到产品.分页返回. 为了方便将要传递的参数直接加载URL中.如:127.0.0.1:8000/classify/0/1/  

  • Django drf分页器的使用详解

    前言 当后台返回的数据过多时,我们就要配置分页器,比如一页最多只能展示10条等等,drf中默认配置了3个分页面 PageNumberPagination:基础分页器,性能略差 LimitOffsetPagination:偏移分页器 CursorPagination:游标分页器,性能强大 PageNumberPagination 基础分页器PageNumberPagination,数据量越大性能越差. 首先我们在app中创建一个pagination.py文件,然后自定义一个分页器类,继承自Page

  • Django分页器的用法你都了解吗

    Django是一个大而全的框架.需要明确的是,传参进行分页获取分页后的数据,一般都是通过向服务器发送get请求的方式实现的,在向后端服务发送查看数据的同时可以携带一个或多个参数并发送get请求来实现分页查看功能 前面总结过drf框架中分页器的使用,本文主要介绍在利用Django开发MVT模型项目时分页器的使用 1.准备基础数据 设计表模型 为了体现分页的效果,需要先创建一个表并准备较多数据,模型如下 from django.db import models # Create your model

  • Django原生sql也能使用Paginator分页的示例代码

    django-pagination这是一个python包,来自github上的一个项目,很容易用. 不过这是一个懒人工具,好吧(工具理性).不过当一个页面有多处需要采用分页的话,就行不通了,要么修改django-pagination的源码,改变它的url指向,不过我没研究,当工程涉及到迁移时,要知道要安装各种东西本来就是个缺点,还要再修改源码,那就得不偿失.因而转战django自带的分页插件--Paginator. Paginator其实只需要实现两个方法`count`和`__getslice_

  • Django分页器的用法详解

    Django是一个大而全的框架.需要明确的是,传参进行分页获取分页后的数据,一般都是通过向服务器发送get请求的方式实现的,在向后端服务发送查看数据的同时可以携带一个或多个参数并发送get请求来实现分页查看功能 1.准备基础数据 设计表模型 为了体现分页的效果,需要先创建一个表并准备较多数据,模型如下 from django.db import models # Create your models here. class Book(models.Model): title = models.C

  • Django使用paginator插件实现翻页功能的实例

    这里需要用到一个Django插件:django-pagination 安装 打开控制台 输入 pip install dj-pagination 实现代码: from django.shortcuts import render from django.core.paginator import Paginator from huxiu.models import Article # Create your views here. def index(request): article_list

  • 三步实现Django Paginator分页的方法

    Django提供了一个新的类来帮助管理分页数据,这个类存放在django/core/paginator.py.它可以接收列表.元组或其它可迭代的对象.本文将分三步介绍Django Paginator 分页的实现步骤 一.通过模型创建Subject Django models from django.db import models class Subject(models.Model): """学科""" no = models.AutoFiel

随机推荐