Ajax实现订单管理

1. 订单数据模型

""" 订单表 """
class Order(models.Model):
    oid = models.CharField(verbose_name="订单编号", max_length=64)
    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 = models.ForeignKey(verbose_name="管理员", to="Admin", on_delete=models.CASCADE)

2. 模态对话框(添加订单)

class OrderModelForm(BootStrapModelForm):
    class Meta:
        model = models.Order
        # fields = '__all__'
        exclude = ['oid', 'admin']


""" 添加订单(Ajax请求) """
@csrf_exempt
def order_add(request):
    form = OrderModelForm(data=request.POST)
    if form.is_valid():
        # 额外增加一些不是用户输入的值(自己计算出来)
        form.instance.oid = datetime.now().strftime('%Y%m%d%H%M%S') + str(random.randint(1000,9999))
        form.instance.admin_id = request.session['info']['id']
        # 保存到数据库中
        form.save()
        return JsonResponse({'status': True})
    
    return JsonResponse({'status': False, 'error': form.errors})
<div class="container">
  <div>
    <input
      type="button"
      value="新建订单(data属性调用)"
      class="btn btn-primary"
      data-toggle="modal"
      data-target="#myModal"
    />
    <input
      id="btnAdd"
      type="button"
      value="新建订单(JS调用)"
      class="btn btn-primary"
    />
  </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">&times;</span>
        </button>
        <h4 class="modal-title" id="myModalLabel">新建订单</h4>
      </div>
      <div class="modal-body">
        <form id="formModalAdd">
          <div class="clearfix">
            {% for field in form %}
            
{{ field }}
{% 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>
<script type="text/javascript">
  $(function () {
    bindBtnAddEvent();
    bindBtnSaveEvent();
  });

  function bindBtnAddEvent() {
    $("#btnAdd").click(function () {
      // 点击新建按钮,显示对话框
      $("#myModal").modal("show");
    });
  }

  function bindBtnSaveEvent() {
    $("#btnSave").click(function () {
      $(".error-msg").empty();
      $.ajax({
        url: "/order/add/",
        type: "post",
        data: $("#formModalAdd").serialize(),
        dataType: "JSON",
        success: function (res) {
          //   console.log(res);
          if (res.status) {
            // alert("创建成功");
            // 清空表单
            $("#formModalAdd")[0].reset();
            // 关闭对话框
            $("#myModal").modal("hide");
            // 刷新页面
            location.reload();
          } else {
            $.each(res.error, function (name, errorList) {
              $("#id_" + name)
                .next()
                .text(errorList[0]);
            });
          }
        },
      });
    });
  }
</script>

3. 订单列表

<div class="panel panel-default">
<div class="panel-heading">
  <span class="glyphicon glyphicon-list" aria-hidden="true"></span>
  订单列表
</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 obj in queryset %}
    
      {{ obj.id }}
      {{ obj.oid }}
      {{ obj.title }}
      {{ obj.price }}
      {{ obj.get_status_display }}
      {{ obj.admin.username }}
      
        编辑
        删除
      
    
    {% endfor %}
  </tbody>
</table>
</div>

<div class="clearfix">
<ul class="pagination">
  {{ page_string }}
</ul>
</div>
""" 订单列表 """
def order_list(request):
    queryset = models.Order.objects.all().order_by('-id')
    page_object = Pagination(request, queryset)
    form = OrderModelForm()

    context = {
        "form": form,
        "queryset": page_object.page_queryset,  # 分页后的数据
        "page_string": page_object.html(),  # 分页的字符串"
    }

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

4. 删除订单

<td>
<a href="#" class="btn btn-primary btn-xs">编辑</a>
<input
  uid="{{ obj.id }}"
  class="btn btn-danger btn-xs btn-delete"
  type="button"
  value="删除"
/>
</td>
<!-- 删除订单(对话框) -->
<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">
      <h4>警告:删除订单!</h4>
      <p>
        删除订单后无法恢复 且
        所有关联的相关数据都会被删除,是否确定要删除该订单?
      </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>
function bindBtnDeleteEvent() {
$(".btn-delete").click(function () {
  // alert('点击了删除');
  // 显示删除对话框
  $("#deleteModal").modal("show");
  // 获取当前行的ID并赋值给全局变量
  DELETE_ID = $(this).attr("uid");
});
}
function bindBtnConfirmDeleteEvent() {
$("#btnConfirmDelete").click(function () {
  // 点击确认删除按钮,将全局变量中设置的那个要删除的ID发送到后台
  $.ajax({
    url: "/order/delete/",
    type: "GET",
    data: {
      uid: DELETE_ID,
    },
    dataType: "JSON",
    success: function (res) {
      if (res.status) {
        // 隐藏删除对话框
        // $("#deleteModal").modal("hide");
        // 当前一行的数据删除(刷新页面)
        // location.reload();
        // $("tr[uid='" + DELETE_ID + "'']").remove();
        // 要删除的ID置空
        // DELETE_ID = 0;
        location.reload();
      } else {
        // 删除失败
        alert(res.error);
      }
    },
  });
});
}

5. 编辑订单

想要去数据库中获取数据库时:对象 / 字典 / queryset

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

实现

<input
  id="btnAdd"
  type="button"
  value="新建订单(JS调用)"
  class="btn btn-success"
/>
<td>
<input
  uid="{{ obj.id }}"
  type="button"
  class="btn btn-primary btn-xs btn-edit"
  value="编辑"
/>
<input
  uid="{{ obj.id }}"
  class="btn btn-danger btn-xs btn-delete"
  type="button"
  value="删除"
/>
</td>
<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">&times;</span>
        </button>
        <h4 class="modal-title" id="myModalLabel">新建订单</h4>
      </div>
      <div class="modal-body">
        <form id="formModalAdd">
          <div class="clearfix">
            {% for field in form %}
            
{{ field }}
{% 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>
function bindBtnAddEvent() {
$("#btnAdd").click(function () {
  // 将正在编辑的ID设置为空
  EDIT_ID = undefined;

  // 清空对话框中的数据
  $("#formModalAdd")[0].reset();

  // 修改对话框标题
  $("#myModalLabel").text("新建订单");

  // 点击新建按钮,显示对话框
  $("#myModal").modal("show");
});
}
function bindBtnSaveEvent() {
$("#btnSave").click(function () {
  $(".error-msg").empty();

  if (EDIT_ID) {
    // 编辑数据的Ajax请求
    doEdit();
  } else {
    // 新增数据的Ajax请求
    doAdd();
  }
});
}
function doEdit() {
$.ajax({
  url: "/order/edit/?uid=" + EDIT_ID,
  type: "post",
  data: $("#formModalAdd").serialize(),
  dataType: "JSON",
  success: function (res) {
    //   console.log(res);
    if (res.status) {
      // alert("创建成功");
      // 清空表单
      $("#formModalAdd")[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 doAdd() {
$.ajax({
  url: "/order/add/",
  type: "post",
  data: $("#formModalAdd").serialize(),
  dataType: "JSON",
  success: function (res) {
    //   console.log(res);
    if (res.status) {
      // alert("创建成功");
      // 清空表单
      $("#formModalAdd")[0].reset();
      // 关闭对话框
      $("#myModal").modal("hide");
      // 刷新页面
      location.reload();
    } else {
      $.each(res.error, function (name, errorList) {
        $("#id_" + name)
          .next()
          .text(errorList[0]);
      });
    }
  },
});
}
function bindBtnEditEvent() {
$(".btn-edit").click(function () {
  // 清空对话框中的数据
  $("#formModalAdd")[0].reset();

  var uid = $(this).attr("uid");
  EDIT_ID = uid;
  // 发送Ajax区后端获取当前行的相关数据
  $.ajax({
    url: "/order/detail/",
    type: "get",
    data: {
      uid: uid,
    },
    dataType: "JSON",
    success: function (res) {
      if (res.status) {
        // 将数据赋值到对话框中的标签
        $.each(res.data, function (name, value) {
          $("#id_" + name).val(value);
        });

        // 修改对话框标题
        $("#myModalLabel").text("编辑订单");

        // 点击编辑按钮,显示对话框
        $("#myModal").modal("show");
      } else {
        alert(res.error);
      }
    },
  });
});
}

评论