• Django+BootstrapTable实现数据的增删改查


    工程目录如下:

    一、查:

    index.html:

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        {% load static %}
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <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>
    </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: '/blog/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" οnclick="deleteData(' + row.id + ')">删除</button>';
                        }
                    }
                ],
                onLoadError: function () {
                    toastr.error("数据加载失败!", "错误提示");
                },
                onClickRow: function (row, $element) {
                    //    EditViewById(id, 'view');
                }
            });
        </script>
    </body>
    
    </html>

    models.py:

    from django.db import models
    from django.utils import timezone
    
    # Create your models here.
    class Article(models.Model):
        title = models.CharField(max_length=32, default='Title')
        content = models.TextField(null = True)
        create_time = models.DateTimeField(default=timezone.now)
    

    blog/views.py:

    from django.shortcuts import render
    from django.views.decorators import csrf
    from django.http import HttpResponse
    from . import models
    from django.views.decorators.csrf import csrf_exempt
    import json
    
    # Create your views here.
    
    @csrf_exempt
    def index(request):
        return render(request, 'index.html')
    
    @csrf_exempt
    def all(request):
        if request.method == 'GET':
            page_size = int(request.GET['pageSize'])
            page_number = int(request.GET['pageNumber'])
    
            total = models.Article.objects.count()
            articles = models.Article.objects.order_by('-id')[(page_number-1)*page_size:page_number*page_size]
            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')

    blog/urls.py:

    from django.urls import path, include
    from . import views
    
    urlpatterns = [
       path('all/', views.all),
    ]
    

    demo7/urls.py:

    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('blog/', include('blog.urls'))
    ]

    二、增:

    post.html:

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        {% load static %}
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <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>
    </head>
    
    <body>
        <form action="" method="POST" class="form-horizontal" style="padding: 20px;">
            <div class="form-group">
                <label for="inputEmail3" class="col-sm-2 control-label">标题:</label>
                <div class="col-sm-10">
                    <input type="text" id="title" class="form-control" />
                </div>
            </div>
    
            <div class="form-group">
                <label for="inputEmail3" class="col-sm-2 control-label">内容:</label>
                <div class="col-sm-10">
                    <textarea id="content" class="form-control"></textarea>
                </div>
            </div>
    
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button id="submit-button" type="submit" class="btn btn-default">提交</button>
                </div>
            </div>
        </form>
    
        <div style="padding: 20px;">
            <table id="articles-table" data-toggle="table" class="table table-bordered table-striped"></table>
        </div>
    
        <script>
            $("#submit-button").click(function () {
                $.ajax({
                    cache: false,
                    type: "POST",
                    url: "/blog/add_article/",
                    //traditional: true, //加上此项可以传数组
                    dataType: 'json',
                    data: { title: $("#title").val(), content: $("#content").val() },
                    success: function (data) {
                        if (data.ret) {
                            toastr.success("数据添加成功!", "成功提示!");
                            $articlesTable.bootstrapTable("refresh");
                        }
                    }
                });
            })
    
            var $articlesTable = $('#articles-table').bootstrapTable('destroy').bootstrapTable({
                url: '/blog/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" οnclick="deleteData(' + row.id + ')">删除</button>';
                        }
                    }
                ],
                onLoadError: function () {
                    toastr.error("数据加载失败!", "错误提示");
                },
                onClickRow: function (row, $element) {
                    //    EditViewById(id, 'view');
                }
            });
        </script>
    </body>
    
    </html>

    blog/urls.py:

    from django.urls import path, include
    from . import views
    
    urlpatterns = [
       path('index/', views.index),
       path('add_article/', views.add_article),
       path('add_page/', views.add_page),
       path('all/', views.all),
    ]
    

    blog/views.py:

    from django.shortcuts import render
    from django.views.decorators import csrf
    from django.http import HttpResponse
    from . import models
    from django.views.decorators.csrf import csrf_exempt
    import json
    
    # Create your views here.
    @csrf_exempt
    def add_page(request):
        return render(request, 'post.html')
    
    @csrf_exempt
    def all(request):
        if request.method == 'GET':
            page_size = int(request.GET['pageSize'])
            page_number = int(request.GET['pageNumber'])
    
            total = models.Article.objects.count()
            articles = models.Article.objects.order_by('-id')[(page_number-1)*page_size:page_number*page_size]
            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')
    
    @csrf_exempt
    def add_article(request):
        ctx ={}
        if request.POST:
            ctx['title'] = request.POST['title']
            ctx['content'] = request.POST['content']
            test1  = models.Article(title=ctx['title'], content=ctx['content'])
            test1.save()
            
            data = {'ret': True, 'msg': '数据提交成功!'}
            return HttpResponse(json.dumps(data), content_type="application/json")

    三、删:

    post.html:

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        {% load static %}
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <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>
    </head>
    
    <body>
        <form action="" method="POST" class="form-horizontal" style="padding: 20px;">
            <div class="form-group">
                <label for="inputEmail3" class="col-sm-2 control-label">标题:</label>
                <div class="col-sm-10">
                    <input type="text" id="title" class="form-control" />
                </div>
            </div>
    
            <div class="form-group">
                <label for="inputEmail3" class="col-sm-2 control-label">内容:</label>
                <div class="col-sm-10">
                    <textarea id="content" class="form-control"></textarea>
                </div>
            </div>
    
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button id="submit-button" type="submit" class="btn btn-default">提交</button>
                </div>
            </div>
        </form>
    
        <div style="padding: 20px;">
            <table id="articles-table" data-toggle="table" class="table table-bordered table-striped"></table>
        </div>
    
        <script>
            $("#submit-button").click(function () {
                $.ajax({
                    cache: false,
                    type: "POST",
                    url: "/blog/add_article/",
                    //traditional: true, //加上此项可以传数组
                    dataType: 'json',
                    data: { title: $("#title").val(), content: $("#content").val() },
                    success: function (data) {
                        if (data.ret) {
                            toastr.success("数据添加成功!", "成功提示!");
                            $articlesTable.bootstrapTable("refresh");
                        }
                    }
                });
            })
    
            var $articlesTable = $('#articles-table').bootstrapTable('destroy').bootstrapTable({
                url: '/blog/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: 'id',
                        title: 'ID'
                    }, {
                        field: 'title',
                        title: '标题',
                         '12%'
                    }, {
                        field: 'content',
                        title: '内容',
                         '62%'
                    }, {
                        field: 'create_time',
                        title: '创建时间',
                         '10%'
                    }, {
                        title: '删除',
                        formatter: function (value, row, index) {
                            //return `<a class="btn btn-primary btn-xs" οnclick="alert(123);">aaa删除</a>`;
                              return `<a class="btn btn-primary btn-xs" onclick="deleteData(${row.id});">aaa删除</a>`;
                        }
                    }
                ],
                onLoadError: function () {
                    toastr.error("数据加载失败!", "错误提示");
                },
                onClickRow: function (row, $element) {
                    //    EditViewById(id, 'view');
                }
            });
    
            // 删除
            function deleteData(id){
                console.log(id);
                $.ajax({
                    cache: false,
                    type: "POST",
                    url: "/blog/delete_article/",
                    //traditional: true, //加上此项可以传数组
                    dataType: 'json',
                    data: { id },
                    success: function (data) {
                        if (data.ret) {
                            toastr.success(data.msg, "成功提示!");
                            $articlesTable.bootstrapTable("refresh");
                        }
                    }
                });
            }
        </script>
    </body>
    
    </html>

    其中 

    return `<a class="btn btn-primary btn-xs" onclick="deleteData(${row.id});">aaa删除</a>`;

    是关键。

    view.py:

    from django.shortcuts import render
    from django.views.decorators import csrf
    from django.http import HttpResponse
    from . import models
    from django.views.decorators.csrf import csrf_exempt
    import json
    
    # Create your views here.
    @csrf_exempt
    def add_page(request):
        return render(request, 'post.html')
    
    @csrf_exempt
    def all(request):
        if request.method == 'GET':
            page_size = int(request.GET['pageSize'])
            page_number = int(request.GET['pageNumber'])
    
            total = models.Article.objects.count()
            articles = models.Article.objects.order_by('-id')[(page_number-1)*page_size:page_number*page_size]
            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')
    
    @csrf_exempt
    def add_article(request):
        ctx ={}
        if request.POST:
            ctx['title'] = request.POST['title']
            ctx['content'] = request.POST['content']
            test1  = models.Article(title=ctx['title'], content=ctx['content'])
            test1.save()
            
            data = {'ret': True, 'msg': '数据提交成功!'}
            return HttpResponse(json.dumps(data), content_type="application/json")
    
    @csrf_exempt
    def delete_article(request):
        article = models.Article.objects.get(id=request.POST['id'])
        article.delete()
        data = {'ret': True, 'msg': '删除成功!'}
        return HttpResponse(json.dumps(data), content_type='application/json')

    其中:

    @csrf_exempt
    def delete_article(request):
        article = models.Article.objects.get(id=request.POST['id'])
        article.delete()
        data = {'ret': True, 'msg': '删除成功!'}
        return HttpResponse(json.dumps(data), content_type='application/json')

    是关键。

    blog/urls.py:

    from django.urls import path, include
    from . import views
    
    urlpatterns = [
       path('add_article/', views.add_article),
       path('add_page/', views.add_page),
       path('all/', views.all),
       path('delete_article/', views.delete_article),
    ]
    

    四、改:

    1、首先通过id获取相关内容,然后将修改后的内容提交给该id对应的内容。

    post.html:

    `<a class="btn btn-primary btn-xs" onclick="modifyData(${row.id});">修改</a>`
            // 修改
            function modifyData(id) {
                $("#modify-modal").modal("show");
                $("#modify-modal-id").val(id);
    
                $.ajax({
                    cache: false,
                    type: "POST",
                    url: "/blog/query_article/",
                    //traditional: true, //加上此项可以传数组
                    dataType: 'json',
                    data: { id },
                    success: function (data) {
                        if (data.ret) {
                            $("#modify-modal-title").val(data.data.title);
                            $("#modify-modal-content").val(data.data.content);
                        }
                    }
                });
            }
    $("#modify-modal-form-submit").click(function(e){
                e.preventDefault();
                $.ajax({
                    cache: false,
                    type: "POST",
                    url: "/blog/modify_article/",
                    //traditional: true, //加上此项可以传数组
                    dataType: 'json',
                    data: { id: $("#modify-modal-id").val(), title: $("#modify-modal-title").val(), content: $("#modify-modal-content").val() },
                    success: function (data) {
                        if (data.ret) {
                            toastr.success(data.msg, "成功提示");
                            $("#modify-modal").modal("hide");
                            $articlesTable.bootstrapTable("refresh");
                        }
                    }
                });

    blog/views.py:

    @csrf_exempt
    def query_article(request):
        id = request.POST['id']
        article = models.Article.objects.get(pk=id)
        data = {
            'ret': True,
            'data': {
                'title': article.title,
                'content': article.content
            }
        }
    
        return HttpResponse(json.dumps(data), content_type='application/json')
    
    
    @csrf_exempt
    def modify_article(request):
        id = request.POST['id']
        title = request.POST['title']
        content = request.POST['content']
        article = models.Article.objects.get(pk=id)
        article.title = title
        article.content = content
        article.save()
        data={'ret': True, 'msg': '修改文章成功!'}
        return HttpResponse(json.dumps(data), content_type='application/json')

    blog/urls.py:

       path('query_article/', views.query_article),
       path('modify_article/', views.modify_article),

    整个增删改查的代码如下:

    post.html:

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        {% load static %}
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <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>
    </head>
    
    <body>
        <div class="botton-panel">
            <a class="btn btn-success" href="#" role="button" style="color:#ffffff;" id="add-article-button">
                <i class="glyphicon glyphicon-plus"></i>
                <span>添加</span>
            </a>
        </div>
    
        <div style="padding-left: 20px; padding-right: 20px;">
            <table id="articles-table" data-toggle="table" class="table table-bordered table-striped"></table>
        </div>
    
        <!--modal begin-->
        <div class="modal fade" id="add-article-modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
            aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                            ×
                        </button>
                        <h4 class="modal-title"> 添加文章 </h4>
                    </div>
                    <form id="add-modal-form" class="form-horizontal" action="">
                        <div class="modal-body">
                            <input type="hidden" id="modify-modal-id" />
                            <div class="form-group row">
                                <label
                                    class="col-sm-3 col-md-3 col-lg-3 col-xl-3 control-label font-normal align-right">标题:</label>
                                <div class="col-sm-7 col-md-7 col-lg-7 col-xl-7">
                                    <div class="file-input-container">
                                        <input type="text" id="title" class="form-control" />
                                    </div>
                                </div>
                            </div>
    
                            <div class="form-group row">
                                <label
                                    class="col-sm-3 col-md-3 col-lg-3 col-xl-3 control-label font-normal align-right">内容:</label>
                                <div class="col-sm-7 col-md-7 col-lg-7 col-xl-7">
                                    <div class="file-input-container">
                                        <textarea id="content" class="form-control"></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                            <button type="submit" class="btn btn-success" id="submit-button">发送</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    
        <div class="modal fade" id="modify-modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
            aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                            ×
                        </button>
                        <h4 class="modal-title"> 修改文章 </h4>
                    </div>
                    <form id="modify-modal-form" class="form-horizontal" action="">
                        <div class="modal-body">
                            <input type="hidden" id="modify-modal-id" />
                            <div class="form-group row">
                                <label
                                    class="col-sm-3 col-md-3 col-lg-3 col-xl-3 control-label font-normal align-right">标题:</label>
                                <div class="col-sm-7 col-md-7 col-lg-7 col-xl-7">
                                    <div class="file-input-container">
                                        <input type="text" class="form-control" id="modify-modal-title" />
                                    </div>
                                </div>
                            </div>
    
                            <div class="form-group row">
                                <label
                                    class="col-sm-3 col-md-3 col-lg-3 col-xl-3 control-label font-normal align-right">内容:</label>
                                <div class="col-sm-7 col-md-7 col-lg-7 col-xl-7">
                                    <div class="file-input-container">
                                        <textarea class="form-control" id="modify-modal-content"></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                            <button type="submit" class="btn btn-success" id="modify-modal-form-submit">发送</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <!--modal end-->
    
        <script>
            $("#add-article-button").click(function(){
                $("#add-article-modal").modal("show");
            })
    
            function getCurrentDate() {
                var timeStr = '-';
                var curDate = new Date();
                var curYear = curDate.getFullYear();  //获取完整的年份(4位,1970-????)
                var curMonth = curDate.getMonth() + 1 < 10 ? "0" + (curDate.getMonth() + 1) : curDate.getMonth() + 1;  //获取当前月份(0-11,0代表1月)
                var curDay = curDate.getDate() < 10 ? "0" + curDate.getDate() : curDate.getDate();       //获取当前日(1-31)
                var curWeekDay = curDate.getDay();    //获取当前星期X(0-6,0代表星期天)
                var curHour = curDate.getHours() < 10 ? "0" + curDate.getHours() : curDate.getHours();      //获取当前小时数(0-23)
                var curMinute = curDate.getMinutes() < 10 ? "0" + curDate.getMinutes() : curDate.getMinutes();   // 获取当前分钟数(0-59)
                var curSec = curDate.getSeconds() < 10 ? "0" + curDate.getSeconds() : curDate.getSeconds();      //获取当前秒数(0-59)
                var Current = curYear + timeStr + curMonth + timeStr + curDay + ' ' + curHour + ':' + curMinute + ':' + curSec;
                console.log(Current);
                // this.datetime=Current;
                return Current;
            }
    
            $("#submit-button").click(function (e) {
                e.preventDefault();
    
                $.ajax({
                    cache: false,
                    type: "POST",
                    url: "/blog/add_article/",
                    //traditional: true, //加上此项可以传数组
                    dataType: 'json',
                    data: { title: $("#title").val(), content: $("#content").val() },
                    success: function (data) {
                        if (data.ret) {
                            toastr.success("数据添加成功!", "成功提示!");
                            $articlesTable.bootstrapTable("refresh");
                            $("#add-article-modal").modal("hide");
                        }
                    }
                });
            })
    
            var $articlesTable = $('#articles-table').bootstrapTable('destroy').bootstrapTable({
                url: '/blog/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: 'id',
                        title: 'ID'
                    }, {
                        field: 'title',
                        title: '标题',
                         '12%'
                    }, {
                        field: 'content',
                        title: '内容',
                         '62%'
                    }, {
                        field: 'create_time',
                        title: '创建时间',
                         '10%',
                        formatter(value, row, index) {
                            return value.replace(/"/g, "");
                        }
                    }, {
                        title: '操作',
                        formatter: function (value, row, index) {
                            //return `<a class="btn btn-primary btn-xs" οnclick="alert(123);">aaa删除</a>`;
                            return `<a class="btn btn-primary btn-xs" onclick="deleteData(${row.id});">删除</a>
                                    <a class="btn btn-primary btn-xs" onclick="modifyData(${row.id});">修改</a>
                                    `;
                        }
                    }
                ],
                onLoadError: function () {
                    toastr.error("数据加载失败!", "错误提示");
                },
                onClickRow: function (row, $element) {
                    //    EditViewById(id, 'view');
                }
            });
    
            // 删除
            function deleteData(id) {
                $.ajax({
                    cache: false,
                    type: "POST",
                    url: "/blog/delete_article/",
                    //traditional: true, //加上此项可以传数组
                    dataType: 'json',
                    data: { id },
                    success: function (data) {
                        if (data.ret) {
                            toastr.success(data.msg, "成功提示!");
                            $articlesTable.bootstrapTable("refresh");
                        }
                    }
                });
            }
    
            // 修改
            function modifyData(id) {
                $("#modify-modal").modal("show");
                $("#modify-modal-id").val(id);
    
                $.ajax({
                    cache: false,
                    type: "POST",
                    url: "/blog/query_article/",
                    //traditional: true, //加上此项可以传数组
                    dataType: 'json',
                    data: { id },
                    success: function (data) {
                        if (data.ret) {
                            $("#modify-modal-title").val(data.data.title);
                            $("#modify-modal-content").val(data.data.content);
                        }
                    }
                });
            }
    
            $("#modify-modal-form-submit").click(function (e) {
                e.preventDefault();
                $.ajax({
                    cache: false,
                    type: "POST",
                    url: "/blog/modify_article/",
                    //traditional: true, //加上此项可以传数组
                    dataType: 'json',
                    data: { id: $("#modify-modal-id").val(), title: $("#modify-modal-title").val(), content: $("#modify-modal-content").val(), datetime: getCurrentDate() },
                    success: function (data) {
                        if (data.ret) {
                            toastr.success(data.msg, "成功提示");
                            $("#modify-modal").modal("hide");
                            $articlesTable.bootstrapTable("refresh");
                        }
                    }
                });
            })
        </script>
    </body>
    
    </html>

    blog/views.py:

    from django.shortcuts import render
    from django.views.decorators import csrf
    from django.http import HttpResponse
    from . import models
    from django.views.decorators.csrf import csrf_exempt
    import json
    
    # Create your views here.
    @csrf_exempt
    def index(request):
        return render(request, 'post.html')
    
    @csrf_exempt
    def all(request):
        if request.method == 'GET':
            page_size = int(request.GET['pageSize'])
            page_number = int(request.GET['pageNumber'])
    
            total = models.Article.objects.count()
            articles = models.Article.objects.order_by('-id')[(page_number-1)*page_size:page_number*page_size]
            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')
    
    @csrf_exempt
    def add_article(request):
        ctx ={}
        if request.POST:
            ctx['title'] = request.POST['title']
            ctx['content'] = request.POST['content']
            test1  = models.Article(title=ctx['title'], content=ctx['content'])
            test1.save()
            
            data = {'ret': True, 'msg': '数据提交成功!'}
            return HttpResponse(json.dumps(data), content_type="application/json")
    
    @csrf_exempt
    def delete_article(request):
        article = models.Article.objects.get(id=request.POST['id'])
        article.delete()
        data = {'ret': True, 'msg': '删除成功!'}
        return HttpResponse(json.dumps(data), content_type='application/json')
    
    @csrf_exempt
    def query_article(request):
        id = request.POST['id']
        article = models.Article.objects.get(pk=id)
        data = {
            'ret': True,
            'data': {
                'title': article.title,
                'content': article.content
            }
        }
    
        return HttpResponse(json.dumps(data), content_type='application/json')
    
    
    @csrf_exempt
    def modify_article(request):
        id = request.POST['id']
        title = request.POST['title']
        content = request.POST['content']
        article = models.Article.objects.get(pk=id)
        article.title = title
        article.content = content
        article.save()
        data={'ret': True, 'msg': '修改文章成功!'}
        return HttpResponse(json.dumps(data), content_type='application/json')

    demo7/urls.py:

    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('blog/', include('blog.urls'))
    ]

    blog/urls.py:

    from django.urls import path, include
    from . import views
    
    urlpatterns = [
       path('index/', views.index),
       path('all/', views.all),
       path('add_article/', views.add_article),
       path('delete_article/', views.delete_article),
       path('query_article/', views.query_article),
       path('modify_article/', views.modify_article),
    ]
    

    blog/models.py:

    from django.db import models
    from django.utils import timezone
    
    # Create your models here.
    class Article(models.Model):
        title = models.CharField(max_length=32, default='Title')
        content = models.TextField(null = True)
        create_time = models.DateTimeField(default=timezone.now)
    

    demo7/setting.py:

    """
    Django settings for demo7 project.
    
    Generated by 'django-admin startproject' using Django 2.0.
    
    For more information on this file, see
    https://docs.djangoproject.com/en/2.0/topics/settings/
    
    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/2.0/ref/settings/
    """
    
    import os
    
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    
    
    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = 'mk^y1nl_435!fx7y@za4)06&bfv_07sc!o7phjph%+2gm9uh8i'
    
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True
    
    ALLOWED_HOSTS = []
    
    
    # Application definition
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'blog'
    ]
    
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]
    
    ROOT_URLCONF = 'demo7.urls'
    
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    
    WSGI_APPLICATION = 'demo7.wsgi.application'
    
    
    # Database
    # https://docs.djangoproject.com/en/2.0/ref/settings/#databases
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'demo7', #选择数据库的名称,请确认你的mysql中有这个库
            'USER': 'root',
            'PASSWORD': '666123',
            'HOST': '127.0.0.1', #在通过命令行模式给dj用户授权的时候,指定的主机是localhost,改成127.0.0.1就能正常迁移数据库了。
            'PORT': '3306'
        }
    }
    
    
    # Password validation
    # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
    
    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]
    
    
    # Internationalization
    # https://docs.djangoproject.com/en/2.0/topics/i18n/
    
    LANGUAGE_CODE = 'en-us'
    
    TIME_ZONE = 'UTC'
    
    USE_I18N = True
    
    USE_L10N = True
    
    USE_TZ = True
    
    
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.0/howto/static-files/
    
    STATIC_URL = '/static/'
    
    STATICFILES_DIRS = [ 
        os.path.join(BASE_DIR, "statics"), 
    ]
  • 相关阅读:
    postman: 字符串与数字的转换
    postman:截取字符串字符
    postman:获取txt变量中数据
    postman:参数化外部文件txt、csv、json
    postman:全局变量、环境变量、collection模块变量
    windows下更新python报错permission denied
    vertica 7.0 使用kafka
    Kafka报错-as it has seen zxid 0x83808 our last zxid is 0x0 client must try another server
    vertica 8.0 新特性
    mysql source导入报错ERROR 1366的解决方法
  • 原文地址:https://www.cnblogs.com/samve/p/13171522.html
Copyright © 2020-2023  润新知