13.Django-订单管理

Django-订单管理

订单管理表设计

# 订单管理表
class Order(models.Model):
    """ 订单 """
    oid = models.CharField(verbose_name="订单号", max_length=64, null=False)
    title = models.CharField(verbose_name="名称", max_length=32)
    price = models.IntegerField(verbose_name="价格")

    status_choices = (
        (1, "待支付"),
        (2, "已支付"),
    )

    status = models.SmallIntegerField(verbose_name="状态", choices=status_choices, default=1)
    admin_user = models.ForeignKey(verbose_name="管理员", to="Admin", to_field="username", on_delete=models.SET_NULL, null=True, blank=False, db_column="admin_username")
    # admin_username 自定义了db_column 表字段名称 但 ModelForm中原始字段名称仍为 admin_user_id
    # form.instance.admin_username = request.session["info"]["name"]  # 程序不会报错但无法插入成功

    # form.instance.admin_user_id = request.session["info"]["name"]   # 使用原始字段

python3 manage.py makemigrations
python3 manage.py migrate

订单添加-实现弹出对话框 两种实现试

# 前端\django\myweb\myweb\urls.py
# 订单管理
    path('order/list/', order.order_list)

from django.shortcuts import render

# 前端\django\myweb\blog\views\order.py
def order_list(request):
    return render(request, 'order_list.html')
<!-- 前端\django\myweb\blog\templates\order_list.html -->
{% extends 'layout.html' %}

{% block content %}
<div class="container">
    <div>
        <input type="button" value="新建订单1" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
        <input id="btnAdd" type="button" value="新建订单2" class="btn btn-primary">
    </div>
</div>

<!-- 新建订单1 - 对话框 -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
          <h4 class="modal-title" id="myModalLabel">Modal title</h4>
        </div>
        <div class="modal-body">
          ...
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>

{% endblock %}

{% block script %}
  <script type="text/javascript">
    $(function(){
        bindBtnAddEvent();
    })

    function bindBtnAddEvent(){
        $("#btnAdd").click(function(){
            $("#myModal").modal('show');
        });
    }
  </script>
{% endblock %}

编辑弹窗里的内容,新建订单

# 前端\django\myweb\blog\utils\modelform.py
class BootStrap_no_width:
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环ModelForm中的所有字段,给每个字段的插件设置
        for _, field in self.fields.items():
            # 字段中有属性,保留原来的属性,没有属性,才增加
            if field.widget.attrs:
                field.widget.attrs["class"] = "form-control"
                # field.widget.attrs["style"] = "width: 300px;"
                if  "placeholder" in field.widget.attrs:
                    continue
                else:
                    field.widget.attrs["placeholder"] = field.label
            else:
                field.widget.attrs = {
                    "class": "form-control",
                    # "style": "width: 300px;",
                    "placeholder": field.label
                }
class BootStrapModelForm_order(BootStrap_no_width, forms.ModelForm):
    pass

# 前端\django\myweb\blog\utils\form.py
# 订单管理
class OrderModelForm(BootStrapModelForm_order):
    class Meta:
        model = Order
        fields = "__all__"
        # 排除 oid 订单号,让系统自动生成
        # 排除 admin 管理员, 默认使用当前登录用户为管理员 
        exclude = ["oid", "admin_user"]
<!-- 前端\django\myweb\blog\templates\order_list.html -->
{% extends 'layout.html' %}

{% block content %}
<div class="container">
    <div>
        <input type="button" value="新建订单1" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
        <input id="btnAdd" type="button" value="新建订单2" class="btn btn-primary">
    </div>
</div>

<!-- 修改弹窗接收ModelForm内容 -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">×</span></button>
                <h4 class="modal-title" id="myModalLabel">新建</h4>
            </div>
            <div class="modal-body">
                <form id="formModal" class="form-group" method="post" novalidate>
                    <div class="clearfix">
                        {% for field in form %}
                        <div class="col-xs-6">
                            <div class="form-group">
                                <label>{{ field.label }}: </label>
                                {{ field }}
                                <!-- 显示错误信息 -->
                                <span class="error-msg" style="color: red;position: absolute;"></span>
                            </div>
                        </div>

                        {% endfor %}
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button id="btnSave" type="button" class="btn btn-primary">保存</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block script %}
<script type="text/javascript">
    $(function () {
        bindBtnAddEvent();
        bindBtnSaveEvent();
    })

    function bindBtnAddEvent() {
        $("#btnAdd").click(function () {
            // 添加前先将对话框内容清空
            $("#formModal")[0].reset();

            // 复用myModal对话框,修改对话框标题
            $("#myModalLabel").text("新建")
            // 点击新建按钮,显示对话框
            $("#myModal").modal('show');
        });
    }

    function bindBtnSaveEvent() {
        $("#btnSave").click(function () {
            // 清除错误信息
            $(".error_msg").empty();
            // 向后台发送请求
            $.ajax({
                url: "/order/add/",
                type: "post",
                data: $("#formModal").serialize(),
                dataType: "JSON",
                success: function (res) {
                    if (res.status) {
                        alert("创建成功");
                        // 清空表单 $("#formModal")是Jquery对象-> $("#formModal")[0] DOM对象
                        $("#formModal")[0].reset();
                        // 关闭对话框
                        $("#myModal").modal('hide');
                        // 刷新页面
                        location.reload();
                    } else {
                        // 把错误信息显示在对话框中
                        $.each(res.error, function (name, errorList) {
                            $("#id_" + name).next().text(errorList[0]);
                        })

                    }
                }
            })
        });
    }
</script>
{% endblock %}

显示订单

# 前端\django\myweb\blog\views\order.py
# 订单展示
def order_list(request):
    form = OrderModelForm()

    data_dict = {}
    search_data = request.GET.get('oid', "")   # 有值拿值,没值为空
    if search_data:
        data_dict["oid__contains"] = search_data

    queryset = Order.objects.filter(**data_dict).order_by("-id")  # 倒序

    page_obj = Pagination(request, queryset)

    context = {
        "order_list": page_obj.page_queryset,
        "search_data": search_data,
        "page_string": page_obj.html(),
        "form": form
    }

    return render(request, 'order_list.html', context)
<!-- 前端\django\myweb\blog\templates\order_list.html -->

{% extends 'layout.html' %}

{% block content %}
<div class="container">
    <div class="row">
        <div class="col-lg-6">
            <input type="button" value="新建订单-ModelForm" class="btn btn-primary" data-toggle="modal"
                data-target="#myModal">
            <input id="btnAdd" type="button" value="新建订单-Ajax" class="btn btn-primary">
        </div>
        <div class="col-lg-6">
            <form method="get" action="/order/list/">
                <div class="input-group">
                    <input type="text" class="form-control" placeholder="查询订单号" name="oid" value="{{ search_data }}">
                    <span class="input-group-btn">
                        <button class="btn btn-primary" type="submit"><span class="glyphicon glyphicon-search"
                                aria-hidden="true"></span><strong> 搜索</strong></button>
                    </span>
                </div>
            </form>
        </div>
    </div>

    <!-- 对话框 -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">×</span></button>
                    <h4 class="modal-title" id="myModalLabel">新建</h4>
                </div>
                <div class="modal-body">
                    <form id="formModal" class="form-group" method="post" novalidate>
                        <div class="clearfix">
                            {% for field in form %}
                            <div class="col-xs-6">
                                <div class="form-group">
                                    <label>{{ field.label }}: </label>
                                    {{ field }}
                                    <!-- 显示错误信息 -->
                                    <span class="error-msg" style="color: red;position: absolute;"></span>
                                </div>
                            </div>

                            {% endfor %}
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button id="btnSave" type="button" class="btn btn-primary">保存</button>
                </div>
            </div>
        </div>
    </div>
    <div style="margin-top: 20px;">
        <div class="panel panel-default">
            <div class="panel-heading">
                <strong>
                    <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> 订单列表
                </strong>
            </div>
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>订单号</th>
                        <th>名称</th>
                        <th>价格</th>
                        <th>状态</th>
                        <th>管理员</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for iteam in order_list %}
                    <tr>
                        <th scope="row">{{ iteam.id }}</th>
                        <td>{{ iteam.oid }}</td>
                        <td>{{ iteam.title }}</td>
                        <td>{{ iteam.price }}</td>
                        <td>{{ iteam.get_status_display }}</td>
                        <td>{{ iteam.admin_user.username }}</td>
                        <td>
                            <a class="btn btn-primary btn-xs" href="/order_edit/{{ iteam.id }}/"> 编辑 </a>
                            <a class="btn btn-danger btn-xs" href="/order_del/{{ iteam.id }}/"> 删除 </a>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
    <nav aria-label="page">
        <ul class="pagination">
            {{ page_string }}
            <form method="get" action="/order/list/">
                <div class="input-group col-sm-2" style="display: inline-block;margin-left: 20px;">
                    <span class="input-group-btn">
                        <input type="text" class="form-control" placeholder="页面跳转" name="page">
                        <button class="btn btn-primary" type="submit">>> 跳转</button>
                    </span>
                </div>
            </form>
        </ul>
    </nav>
</div>
{% endblock %}

{% block script %}
<script type="text/javascript">
    $(function () {
        bindBtnAddEvent();
        bindBtnSaveEvent();
    })

    function bindBtnAddEvent() {
        $("#btnAdd").click(function () {
            // 添加前先将对话框内容清空
            $("#formModal")[0].reset();

            // 复用myModal对话框,修改对话框标题
            $("#myModalLabel").text("新建")
            // 点击新建按钮,显示对话框
            $("#myModal").modal('show');
        });
    }

    function bindBtnSaveEvent() {
        $("#btnSave").click(function () {
            // 清除错误信息
            $(".error_msg").empty();
            // 向后台发送请求
            $.ajax({
                url: "/order/add/",
                type: "post",
                data: $("#formModal").serialize(),
                dataType: "JSON",
                success: function (res) {
                    if (res.status) {
                        alert("创建成功");
                        // 清空表单 $("#formModal")是Jquery对象-> $("#formModal")[0] DOM对象
                        $("#formModal")[0].reset();
                        // 关闭对话框
                        $("#myModal").modal('hide');
                        // 刷新表单数据
                        window.location.reload();
                    } else {
                        // 把错误信息显示在对话框中
                        $.each(res.error, function (name, errorList) {
                            $("#id_" + name).next().text(errorList[0]);
                        })

                    }
                }
            })
        });
    }
</script>
{% endblock %}

删除订单

# 删除订单
def order_del(request):
    del_id = request.GET.get("del_id")
    # print(del_id)
    if Order.objects.filter(id=del_id).exists():
        Order.objects.filter(id=del_id).delete()
        return JsonResponse({"status": True})

    data_dict = {"status": False, "error": "删除失败,数据不存在!"}
    return JsonResponse(data_dict)
<!-- 删除-对话框 -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="alert alert-danger alert-dismissible fade in" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
                    aria-hidden="true">×</span></button>
            <h4>警告!是否确定删除?</h4>
            <p style="margin: 15px 0;">删除后,订单数据无法恢复!</p>
            <p style="text-align: right;">
                <button id="btnConfirmDelete" type="button" class="btn btn-danger">确 定</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">取 消</button>
            </p>
        </div>

    </div>
</div>

<input del_id="{{ iteam.id }}" type="button" class="btn btn-danger btn-xs btn-delete" value="删除">

<script type="text/javascript">
    var DELETE_ID;
    $(function () {
        bindBtnAddEvent();
        bindBtnSaveEvent();
        bindBtnDeleteEvent();
        bindBtnConfirmDelete();
    })
    function bindBtnDeleteEvent() {
        $(".btn-delete").click(function () {
            // alert("点击了删除");
            // 显示删除对话框
            $("#deleteModal").modal('show');
            // 获取当前行的ID并赋值给全局变量DELETE_ID
            // var del_id = $(this).attr("del_id");
            // console.log(del_id);
            DELETE_ID = $(this).attr("del_id");
        })
    }

    function bindBtnConfirmDelete() {
        $("#btnConfirmDelete").click(function () {
            // 点击了确认按钮,将全局变量中设置的要删除的id发送到后台
            $.ajax({
                // url: "/order/" + DELETE_ID + "/del/",    // -> /order/12/del/
                url: "/order/del/",
                type: "GET",
                data: {
                    del_id: DELETE_ID
                },
                dataType: "JSON",
                success: function (res) {
                    if (res.status){
                        // alert("删除成功!");
                        // 隐藏删除框
                        // $("#deleteModal").modal('hide');

                        // 在页面上已经删除的数据清理(js方法)
                        // $("tr[del_id='" + DELETE_ID + "']").remove()
                        // 要删除的ID置空
                        // DELETE_ID = 0

                        // 刷新页面
                        location.reload();

                    }else{
                        alert(res.error);
                    }
                }
            })
        })
    }
</script>

编辑订单-对话框显示要编辑的数据

# 编辑订单
def order_detail(request):
    """方式1"""
    # e_id = request.GET.get("e_id")
    # row_object = Order.objects.filter(id=e_id).first()
    # if not row_object:
    #     return JsonResponse({"status": False, "error": "删除失败,数据不存在!"})

    # result = {
    #     "status": True,
    #     "data": {
    #         "title": row_object.title,
    #         "price": row_object.price,
    #         "status": row_object.status
    #     }
    # }

    # return JsonResponse(result)

    """方式2"""
    e_id = request.GET.get("e_id")

    # queryset = Order.objects.all()   # querset对象 queryset = [obj,obj,obj,obj]
    # row_object = Order.objects.filter(id=e_id).first()  # 对象,查询到的当前行所有数据,row_object.id row_object.title row_object.price
    # queryset = Order.objects.filter(id=e_id).values("title","price","status")   # queryset = [{"id": 1, "title": "xxxx"...},{"id": 2, "title": "xxxx"...}]
    # queryset = Order.objects.filter(id=e_id).values_list("title","price","status")  # queryset = [(1,"xxx"...),(2,"xxx"...)...]
    row_dict = Order.objects.filter(id=e_id).values("title","price","status").first()   # 字典 {"id": 1, "title": "xxxx", ...}

    if not row_dict:
        return JsonResponse({"status": False, "error": "删除失败,数据不存在!"})

    result = {
        "status": True,
        "data": row_dict
    }

    return JsonResponse(result)
<script type="text/javascript">
    var DELETE_ID;
    $(function () {
        bindBtnAddEvent();
        bindBtnSaveEvent();
        bindBtnDeleteEvent();
        bindBtnConfirmDelete();
        bindBtnEditEvent();

    })
    function bindBtnEditEvent() {
        $(".btn-edit").click(function () {
            // 获取当前行的ID
            var edit_id = $(this).attr("edit_id")
            // alert("点击了删除");

            // 发送Ajax去后端获取当前行的相关数据
            $.ajax({
                url: "/order/edit/",
                type: "GET",
                data: {
                    e_id: edit_id
                },
                dataType: "JSON",
                success: function(res) {
                    // console.log(res);
                    if (res.status){
                        // console.log(res.data)
                        // 添加前先将对话框内容清空
                        $("#formModal")[0].reset();

                        $.each(res.data, function (name, value) {
                            console.log(res.data)
                            $("#id_" + name).val(value);
                        })

                        // 复用myModal对话框,修改对话框标题
                        $("#myModalLabel").text("编辑")
                        // 显示编辑对话框
                        $("#myModal").modal('show');
                    }else{
                        alert(res.error)
                    }
                }
            })
            // 在对话框中默认看到
        })
    }
</script>

编辑订单-提交数据

<script type="text/javascript">
    var DELETE_ID;
    var EDIT_ID;
    function doAdd() {
        // 向后台发送请求,新建的Ajax请求
        $.ajax({
            url: "/order/add/",
            type: "post",
            data: $("#formModal").serialize(),
            dataType: "JSON",
            success: function (res) {
                if (res.status) {
                    alert("创建成功");
                    // 清空表单 $("#formModal")是Jquery对象-> $("#formModal")[0] DOM对象
                    $("#formModal")[0].reset();
                    // 关闭对话框
                    $("#myModal").modal('hide');
                    // 刷新表单数据
                    location.reload();
                } else {
                    // 把错误信息显示在对话框中
                    $.each(res.error, function (name, errorList) {
                        $("#id_" + name).next().text(errorList[0]);
                    })

                }
            }
        })
    }

    function doEdit() {
        // 向后台发送请求,新建的Ajax请求
        $.ajax({
            url: "/order/edit/" + "?e_id=" + EDIT_ID,
            type: "post",
            data: $("#formModal").serialize(),
            dataType: "JSON",
            success: function (res) {
                if (res.status) {
                    alert("编辑成功");
                    // 清空表单 $("#formModal")是Jquery对象-> $("#formModal")[0] DOM对象
                    $("#formModal")[0].reset();
                    // 关闭对话框
                    $("#myModal").modal('hide');
                    // 刷新表单数据
                    location.reload();
                } else {
                    if (res.tips) {
                        alert(res.tips)
                    } else {
                        // 把错误信息显示在对话框中
                        $.each(res.error, function (name, errorList) {
                            $("#id_" + name).next().text(errorList[0]);
                        })
                    }
                }
            }
        })
    }

    function bindBtnSaveEvent() {
        $("#btnSave").click(function () {
            // 清除错误信息
            $(".error_msg").empty();

            if (EDIT_ID) {
                // 编辑
                doEdit();
            } else {
                // 新建
                doAdd();
            }

        });
    }
</script>
# 编辑订单 提交数据
@csrf_exempt
def order_edit(request):
    e_id = request.GET.get("e_id")

    row_object = Order.objects.filter(id=e_id).first()

    if not row_object:
        return JsonResponse({"status": False, "tips": "数据不存在!"})

    form = OrderModelForm(data=request.POST, instance=row_object)

    if form.is_valid():
        form.save()
        return JsonResponse({"status": True, "error": form.errors})

订单管理完整代码

# 前端\django\myweb\myweb\urls.py

from django.contrib import admin
from django.urls import path, re_path
# from 前端.django.myweb.blog.test import *
from blog.views import depart,user,pretty,administrator,account,task,order
from blog import test

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index_app/', test.index_app),
    path('user_list/', test.user_list),
    path('news/', test.news),
    path('something/', test.something),
    path('orm/', test.orm),

    # 案例 用户列表
    path('info_list/', test.info_list),
    path('info_add/', test.info_add),
    path('info_del/', test.info_del),

    # 员工管理系统-部门管理
    path('depart/list/', depart.depart_list),
    path('depart/add/', depart.depart_add),
    path('depart/del/', depart.depart_del),
    path('depart/<int:nid>/edit/', depart.depart_edit),

    # 员工管理系统-用户管理
    path('users/list/', user.users_list),
    path('users/add/', user.users_add),
    path('users/add_modelform/', user.users_add_modelform),
    path('users/del/', user.users_del),
    path('users/<int:nid>/edit/', user.users_edit),

    # 员工管理系统-靓号管理
    path('pretty/list/', pretty.pretty_list),
    path('pretty/add/', pretty.pretty_add),
    path('pretty/<int:nid>/del/', pretty.pretty_del),
    path('pretty/<int:nid>/edit/', pretty.pretty_edit),

    # 员工管理系统-管理员
    path('admin_list/', administrator.admin_list),
    path('admin_add/', administrator.admin_add),
    path('admin_del/<int:nid>/', administrator.admin_del),
    path('admin_edit/<int:nid>/', administrator.admin_edit),
    path('admin_pwd_reset/<int:nid>/', administrator.admin_pwd_reset),

    # 用户认证
    path('', administrator.admin_list),
    path('login/', account.login),
    path('loginout/', account.loginout),

    # 图片验证码
    path('img/check_code/', account.check_code_img),
    re_path(r'img/check_code/(?P<random>\d+)', account.check_code_img),    # 点击刷新验证码

    # 任务管理
    path('task/list/', task.task_list),
    path('task/ajax/', task.task_ajax),
    path('task/add/', task.task_add),

    # 订单管理
    path('order/list/', order.order_list),
    path('order/add/', order.order_add),
    path('order/del/', order.order_del),
    path('order/detail/', order.order_detail),
    path('order/edit/', order.order_edit),

]
# 前端\django\myweb\blog\views\order.py

from django.shortcuts import render, redirect
from blog.models import Order
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
from blog.utils.form import OrderModelForm
from django.views.decorators.csrf import csrf_exempt
from datetime import datetime
import random
from blog.utils.pagination import Pagination

# 订单展示
def order_list(request):
    form = OrderModelForm()

    data_dict = {}
    search_data = request.GET.get('oid', "")   # 有值拿值,没值为空
    if search_data:
        data_dict["oid__contains"] = search_data

    queryset = Order.objects.filter(**data_dict).order_by("-id")  # 倒序

    page_obj = Pagination(request, queryset)

    context = {
        "order_list": page_obj.page_queryset,
        "search_data": search_data,
        "page_string": page_obj.html(),
        "form": form
    }

    return render(request, 'order_list.html', context)

# 新建订单
@csrf_exempt
def order_add(request):
    """新建订单Ajax请求"""
    form = OrderModelForm(data=request.POST)
    if form.is_valid():
        # print(form.cleaned_data)  # {'title': 'test', 'price': 123, 'status': 1}
        # oid
        # print(datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(1000,9999)))
        form.instance.oid = datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(1000,9999))
        # admin_username 自定义了db_column 但 ModelForm中原始字段名称仍为 admin_user_id
        # print(request.session.items())   # dict_items([('_session_expiry', 604800), ('info', {'id': 1, 'name': 'tang'})])
        # form.instance.admin_username = request.session["info"]["name"]  # 程序不会报错但无法插入成功

        form.instance.admin_user_id = request.session["info"]["name"]   # 需使用原始字段
        # print(form.instance.admin_user_id)
        form.save()
        data_dict = {"status": True}
        return JsonResponse(data_dict)

    data_dict = {"status": False, 'error': form.errors}
    return JsonResponse(data_dict)

# 删除订单
def order_del(request):
    del_id = request.GET.get("del_id")
    # print(del_id)
    if Order.objects.filter(id=del_id).exists():
        Order.objects.filter(id=del_id).delete()
        return JsonResponse({"status": True})

    data_dict = {"status": False, "error": "删除失败,数据不存在!"}
    return JsonResponse(data_dict)

# 编辑订单显示
def order_detail(request):
    """方式1"""
    # e_id = request.GET.get("e_id")
    # row_object = Order.objects.filter(id=e_id).first()
    # if not row_object:
    #     return JsonResponse({"status": False, "error": "删除失败,数据不存在!"})

    # result = {
    #     "status": True,
    #     "data": {
    #         "title": row_object.title,
    #         "price": row_object.price,
    #         "status": row_object.status
    #     }
    # }

    # return JsonResponse(result)

    """方式2"""
    e_id = request.GET.get("e_id")

    # queryset = Order.objects.all()   # querset对象 queryset = [obj,obj,obj,obj]
    # row_object = Order.objects.filter(id=e_id).first()  # 对象,查询到的当前行所有数据,row_object.id row_object.title row_object.price
    # queryset = Order.objects.filter(id=e_id).values("title","price","status")   # queryset = [{"id": 1, "title": "xxxx"...},{"id": 2, "title": "xxxx"...}]
    # queryset = Order.objects.filter(id=e_id).values_list("title","price","status")  # queryset = [(1,"xxx"...),(2,"xxx"...)...]
    row_dict = Order.objects.filter(id=e_id).values("title","price","status").first()   # 字典 {"id": 1, "title": "xxxx", ...}

    if not row_dict:
        return JsonResponse({"status": False, "error": "数据不存在!"})

    print(row_dict)
    result = {
        "status": True,
        "data": row_dict
    }

    return JsonResponse(result)

# 编辑订单 提交数据
@csrf_exempt
def order_edit(request):
    e_id = request.GET.get("e_id")

    row_object = Order.objects.filter(id=e_id).first()

    if not row_object:
        return JsonResponse({"status": False, "tips": "数据不存在!"})

    form = OrderModelForm(data=request.POST, instance=row_object)

    if form.is_valid():
        form.save()
        return JsonResponse({"status": True, "error": form.errors})
<!-- 前端\django\myweb\blog\templates\order_list.html -->

{% extends 'layout.html' %}

{% block content %}
<div class="container">
    <div class="row">
        <div class="col-lg-6">
            <input type="button" value="新建订单-ModelForm" class="btn btn-primary" data-toggle="modal"
                data-target="#myModal">
            <input id="btnAdd" type="button" value="新建订单-Ajax" class="btn btn-primary">
        </div>
        <div class="col-lg-6">
            <form method="get" action="/order/list/">
                <div class="input-group">
                    <input type="text" class="form-control" placeholder="查询订单号" name="oid" value="{{ search_data }}">
                    <span class="input-group-btn">
                        <button class="btn btn-primary" type="submit"><span class="glyphicon glyphicon-search"
                                aria-hidden="true"></span><strong> 搜索</strong></button>
                    </span>
                </div>
            </form>
        </div>
    </div>

    <!-- 新建/编辑-对话框 -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">×</span></button>
                    <h3 class="modal-title" id="myModalLabel">新建/编辑</h3>
                </div>
                <div class="modal-body">
                    <form id="formModal" class="form-group" method="post" novalidate>
                        <div class="clearfix">
                            {% for field in form %}
                            <div class="col-xs-6">
                                <div class="form-group">
                                    <label>{{ field.label }}: </label>
                                    {{ field }}
                                    <!-- 显示错误信息 -->
                                    <span class="error-msg" style="color: red;position: absolute;"></span>
                                </div>
                            </div>

                            {% endfor %}
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button id="btnSave" type="button" class="btn btn-primary">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 删除-对话框 -->
    <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="alert alert-danger alert-dismissible fade in" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
                        aria-hidden="true">×</span></button>
                <h4>警告!是否确定删除?</h4>
                <p style="margin: 15px 0;">删除后,订单数据无法恢复!</p>
                <p style="text-align: right;">
                    <button id="btnConfirmDelete" type="button" class="btn btn-danger">确 定</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">取 消</button>
                </p>
            </div>

        </div>
    </div>

    <div style="margin-top: 20px;">
        <div class="panel panel-default">
            <div class="panel-heading">
                <strong>
                    <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> 订单列表
                </strong>
            </div>
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>订单号</th>
                        <th>名称</th>
                        <th>价格</th>
                        <th>状态</th>
                        <th>管理员</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for iteam in order_list %}
                    <tr del_id="{{ iteam.id }}">
                        <th scope="row">{{ iteam.id }}</th>
                        <td>{{ iteam.oid }}</td>
                        <td>{{ iteam.title }}</td>
                        <td>{{ iteam.price }}</td>
                        <td>{{ iteam.get_status_display }}</td>
                        <td>{{ iteam.admin_user.username }}</td>
                        <td>
                            <input edit_id="{{ iteam.id }}" type="button" class="btn btn-primary btn-xs btn-edit"
                                value="编辑">
                            <input del_id="{{ iteam.id }}" type="button" class="btn btn-danger btn-xs btn-delete"
                                value="删除">
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
    <nav aria-label="page">
        <ul class="pagination">
            {{ page_string }}
            <form method="get" action="/order/list/">
                <div class="input-group col-sm-2" style="display: inline-block;margin-left: 20px;">
                    <span class="input-group-btn">
                        <input type="text" class="form-control" placeholder="页面跳转" name="page">
                        <button class="btn btn-primary" type="submit">>> 跳转</button>
                    </span>
                </div>
            </form>
        </ul>
    </nav>
</div>
{% endblock %}

{% block script %}
<script type="text/javascript">
    var DELETE_ID;
    var EDIT_ID;
    $(function () {
        bindBtnAddEvent();
        bindBtnSaveEvent();
        bindBtnDeleteEvent();
        bindBtnConfirmDelete();
        bindBtnEditEvent();

    })

    function bindBtnAddEvent() {
        $("#btnAdd").click(function () {
            // 将正在编辑的ID置空
            EDIT_ID = undefined;

            // 添加前先将对话框内容清空
            $("#formModal")[0].reset();

            // 复用myModal对话框,修改对话框标题
            $("#myModalLabel").text("新建")
            // 点击新建按钮,显示对话框
            $("#myModal").modal('show');

        });
    }

    function doAdd() {
        // 向后台发送请求,新建的Ajax请求
        $.ajax({
            url: "/order/add/",
            type: "post",
            data: $("#formModal").serialize(),
            dataType: "JSON",
            success: function (res) {
                if (res.status) {
                    alert("创建成功");
                    // 清空表单 $("#formModal")是Jquery对象-> $("#formModal")[0] DOM对象
                    $("#formModal")[0].reset();
                    // 关闭对话框
                    $("#myModal").modal('hide');
                    // 刷新表单数据
                    location.reload();
                } else {
                    // 把错误信息显示在对话框中
                    $.each(res.error, function (name, errorList) {
                        $("#id_" + name).next().text(errorList[0]);
                    })

                }
            }
        })
    }

    function doEdit() {
        // 向后台发送请求,新建的Ajax请求
        $.ajax({
            url: "/order/edit/" + "?e_id=" + EDIT_ID,
            type: "post",
            data: $("#formModal").serialize(),
            dataType: "JSON",
            success: function (res) {
                if (res.status) {
                    alert("编辑成功");
                    // 清空表单 $("#formModal")是Jquery对象-> $("#formModal")[0] DOM对象
                    $("#formModal")[0].reset();
                    // 关闭对话框
                    $("#myModal").modal('hide');
                    // 刷新表单数据
                    location.reload();
                } else {
                    if (res.tips) {
                        alert(res.tips)
                    } else {
                        // 把错误信息显示在对话框中
                        $.each(res.error, function (name, errorList) {
                            $("#id_" + name).next().text(errorList[0]);
                        })
                    }
                }
            }
        })
    }

    function bindBtnSaveEvent() {
        $("#btnSave").click(function () {
            // 清除错误信息
            $(".error_msg").empty();

            if (EDIT_ID) {
                // 编辑
                doEdit();
            } else {
                // 新建
                doAdd();
            }

        });
    }

    function bindBtnDeleteEvent() {
        $(".btn-delete").click(function () {
            // alert("点击了删除");
            // 显示删除对话框
            $("#deleteModal").modal('show');
            // 获取当前行的ID并赋值给全局变量DELETE_ID
            // var del_id = $(this).attr("del_id");
            // console.log(del_id);
            DELETE_ID = $(this).attr("del_id");
        })
    }

    function bindBtnConfirmDelete() {
        $("#btnConfirmDelete").click(function () {
            // 点击了确认按钮,将全局变量中设置的要删除的id发送到后台
            $.ajax({
                // url: "/order/" + DELETE_ID + "/del/",    // -> /order/12/del/
                url: "/order/del/",
                type: "GET",
                data: {
                    del_id: DELETE_ID
                },
                dataType: "JSON",
                success: function (res) {
                    if (res.status) {
                        // alert("删除成功!");
                        // 隐藏删除框
                        // $("#deleteModal").modal('hide');

                        // 在页面上已经删除的数据清理(js方法)
                        // $("tr[del_id='" + DELETE_ID + "']").remove()
                        // 要删除的ID置空
                        // DELETE_ID = 0

                        // 刷新页面
                        location.reload();

                    } else {
                        alert(res.error);
                    }
                }
            })
        })
    }

    function bindBtnEditEvent() {
        $(".btn-edit").click(function () {
            // 获取当前行的ID
            var edit_id = $(this).attr("edit_id");
            // alert("点击了删除");
            // 赋值给全局变量
            EDIT_ID = edit_id;
            // 复用复用myModal对话框,打开对话框前清空编辑时填入的数据
            $("#formModal")[0].reset();

            // 发送Ajax去后端获取当前行的相关数据
            $.ajax({
                url: "/order/detail/",
                type: "GET",
                data: {
                    e_id: edit_id
                },
                dataType: "JSON",
                success: function (res) {
                    // console.log(res);
                    if (res.status) {
                        // console.log(res.data)
                        // 添加前先将对话框内容清空
                        $("#formModal")[0].reset();

                        $.each(res.data, function (name, value) {
                            console.log(res.data)
                            $("#id_" + name).val(value);
                        })

                        // 复用myModal对话框,修改对话框标题
                        $("#myModalLabel").text("编辑")
                        // 显示编辑对话框
                        $("#myModal").modal('show');

                    } else {
                        alert(res.error)
                    }
                }
            })
            // 在对话框中默认看到
        })
    }
</script>
{% endblock %}