zoukankan      html  css  js  c++  java
  • Django+BootstrapTable实现表格分页

    models.py:

    from django.db import models
    
    # Create your models here.
    class Article(models.Model):
        title = models.CharField('标题', max_length=64)
        content = models.TextField('内容', null=True)
        create_time = models.DateTimeField('发布时间')
        
        class Meta:
            verbose_name = '文章'
            verbose_name_plural = '文章'
        
        def __str__(self):
            return self.title

    admin.py:

    from django.contrib import admin
    from .models import Article
    
    class ArticleAdmin(admin.ModelAdmin):
        list_display = ('id', 'title', 'create_time', )
        list_display_link = ('title',)
        
    # Register your models here.
    admin.site.register(Article, ArticleAdmin)

    views.py:

    #--*--encoding='utf8'--*--
    from django.shortcuts import render
    from django.http import HttpResponse
    from .models import Article
    import json
    from django.views.decorators.csrf import csrf_exempt
    
    # Create your views here.
    def index(request):
        return render(request, 'index.html')
    
    @csrf_exempt
    def all(request):
        if request.method == 'GET':
            pageSize = int(request.GET.get('pageSize'))
            pageNumber = int(request.GET.get('pageNumber'))
            searchText = request.GET.get('searchText')
            sortName = request.GET.get('sortName')
            sortOrder = request.GET.get('sortOrder')
        
        total = Article.objects.all().count()
        articles = Article.objects.order_by('-id')[(pageNumber-1)*pageSize:(pageNumber)*pageSize]
        rows = []
        data = {"total": total, "rows": rows}
        for article in articles:
            rows.append({'id': article.id, 'title': article.title, 'content': article.content})
            
        return HttpResponse(json.dumps(data), content_type="application/json")
    
    def add(request):
        return render(request, 'add.html')
    
    @csrf_exempt
    def deal(request):
        if request.method == "POST":
            title = request.POST.get('title')
            content = request.POST.get('content')
            article = Article(title = title, content = content)
            article.save()
            ret = {"ret": 0, 'title': title, 'content': content}
            return HttpResponse(json.dumps(ret))
    
    def article(request, article_id):
        article = Article.objects.get(pk = article_id)
        return render(request, 'article.html', {'article': article})
    
    def get_an_apple(request): 
        resp = {'errorcode': 100, 'detail': 'Get success'} 
        return HttpResponse(json.dumps(resp), content_type="application/json")
    
    @csrf_exempt
    def delete(request):
        return_dict = {"ret": True, "errMsg": "", "rows": [], "total": 0}
        article_id = request.POST.get('id')
        article = Article.objects.get(id = article_id)
        article.delete()
        return HttpResponse(json.dumps(return_dict))
    

    其中all函数是关键。

    index.html:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    {% load staticfiles %}
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="{% static 'libs/bootstrap/css/bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'libs/toastr/css/toastr.css' %}">
    <link rel="stylesheet" href="{% static 'libs/bootstrap-table-master/bootstrap-table.css' %}">
    <script src="{% static 'libs/jquery/jquery-1.11.2.min.js' %}"></script>
    <script src="{% static 'libs/bootstrap/js/bootstrap.min.js' %}"></script>
    <script src="{% static 'libs/toastr/js/toastr.min.js' %}"></script>
    <script src="{% static 'libs/bootstrap-table-master/bootstrap-table.js' %}"></script>
    <script src="{% static 'libs/bootstrap-table-master/locale/bootstrap-table-zh-CN.js' %}"></script>
    <title>Django后台管理系统</title>
    </head>
    
    <body>
    
    <div style="padding: 20px;">
        <table id="articles-table" data-toggle="table" class="table table-bordered table-striped"></table>
    </div>
    
    <script>
    var $articlesTable = $('#articles-table').bootstrapTable('destroy').bootstrapTable({
        url: '/article/all/',
        method: 'GET',
        dataType: "json",
        uniqueId: 'id',
        striped: false,
        cache: false,
        sortName: 'id',
        sortable: false,
        sortOrder: 'desc',
        sidePagination: "server",
        undefinedText: '--',
        singleSelect: false,
        toolbar: '#soft-toolbar',
        search: false,
        strictSearch: true,
        clickToSelect: true,
        pagination: true,
        pageNumber: 1,
        pageSize: 5,
        pageList: [5, 10, 20, 50, 100],
        paginationPreText: "上一页",
        paginationNextText: "下一页",
        queryParamsType: "",
        queryParams : function (params) {
            var temp = {
                'pageSize' : params.pageSize,
                'pageNumber' : params.pageNumber,
                'searchText': params.searchText,
                'sortName': params.sortName,
                'sortOrder': params.sortOrder
            };
            return temp;
        },
        columns: [
            {
                checkbox: true
            },{
                field: 'title',
                title:'标题',
                 '12%'
            },{
                field: 'content',
                title:'内容',
                 '62%'
            },{
                field: 'create_time',
                title:'创建时间',
                 '10%'
            },{
                title:'删除',
                formatter: function(value, row, index){
                    return '<button type="button" class="btn btn-primary btn-xs" onclick="deleteData(' + row.id + ')">删除</button>';
                }
            }
        ],
        onLoadError: function () {
            toastr.error("数据加载失败!", "错误提示");
        },
        onClickRow: function (row, $element) {
            //    EditViewById(id, 'view');
        }
    });
    
    function deleteData(id){
        $.ajax({
            type: "POST",
            url: '/article/delete/',
            data: {id: id},
            dataType: "json",
            success: function(data){
                console.log(data);
                if(data.ret){
                    toastr.success('删除成功!', '成功提示');
                    $articlesTable.bootstrapTable('refresh');
                }
            },
            error: function(data){
                console.log(data);
            }
        });
    }
    </script>
    </body>
    </html>   

    以上四个文件中,views.py和index.html文件是关键。

  • 相关阅读:
    win7 iis7 配置如何让局域网内其它用户访问
    WPF依赖项属性详解一
    项目管理SOW(工作说明书)
    新建silverlight 4 应用程序时出错:需要更新 microsoft visual studio 以面向 silverlight4
    WPF触发器(trigger)详解
    public,private,protected,internal作用
    抽象类,密封类及类成员
    java8 lanbda表达式对list对象去重,对象属性转成string
    window10环境ngnix配置https记录
    java动态调用webservice(.asmx?wsdl)
  • 原文地址:https://www.cnblogs.com/samve/p/11273288.html
Copyright © 2011-2022 走看看