1. 在 urls.py 中编辑url
path('order_delete',views.order_delete),
2. 在 views.py 中编写后端代码
def order_delete(request): uid = request.GET.get('uid') exists = models.Order.objects.filter(id=uid).exists() if not exists: return JsonResponse({"status": False, 'error': '数据不存在'}) models.Order.objects.filter(id=uid).delete() return JsonResponse({"status": True})
3. 编写 HTML 前端代码
<div align="center"> <h1>数据列表</h1> <hr> {% csrf_token %} <table class="table table-hover"> <thead> <tr> <td>id</td> <td>订单号</td> <td>名称</td> <td>价格</td> <td>状态</td> <td>管理员</td> <td>操作</td> </tr> </thead> <tbody> {% for i in obj %} <tr uid="{{ i.id }}"> <td>{{ i.id }}</td> <td>{{ i.odi }}</td> <td>{{ i.title }}</td> <td>{{ i.price }}</td> <td>{{ i.get_status_display }}</td> <td>{{ i.admin.account }}</td> <td> <input uid="{{ i.id }}" class="btn btn-danger btn-xs btn-delete" type="button" value="删除" > </td> </tr> {% endfor %} </tbody> </table> </div> <!-- 删除对话框 --> <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="alert alert-danger alert-dismissible fade in" role="alert"> <h4>是否确认删除?</h4> <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><!-- /.modal-dialog --> </div><!-- /.modal --> <script src="{% static 'jquery-3.7.0.min.js' %}"></script> <script src="{% static '/bootstrap/js/bootstrap.min.js' %}"></script> // 全局变量 var DELETE_ID; $(function () { bindBtnDeleteEvent(); bindBtnConfirmDeleteEvent(); }) function bindBtnDeleteEvent() { $('.btn-delete').click(function () { $('#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){ alert("删除成功"); //关闭对话框 $('#deleteModal').modal('hide'); // 当前一行数据删除(js) // $("tr[uid='"+ DELETE_ID + "']").remove(); // 要删除的id置空 DELETE_ID=0; // 页面刷新 location.reload(); }else { // 删除失败 alert(res.error); } } }) }) }
标签:function,uid,删除,django,Ajax,ID,id,delete From: https://www.cnblogs.com/p4567/p/17777981.html