文章目录
订单管理
实现对话框弹框中内容特殊数据输入
对话框u化删除
从数据库中获取数据的类型编辑
完好代码
订单管理
实现对话框
新建表:
models.py- classOrder(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)
复制代码 urls.py
orderlist.html
分别用jquery和js里的方法实现对话框
第一种方式: 官网自带方式
第二种方式: javascript实现- {% block script %}<script type="text/javascript">
- $(function(){
- bindBtnAddEvent();})
- function bindBtnAddEvent(){
- $("#btnAdd").click(function(){
- $("#myModal").modal('show');});}</script>{% endblock %}
复制代码
弹窗的完好html代码- {% extends 'layout.html' %}
- {% block content %}
- <divclass="container"><div><inputtype="button"value="新建订单1"class="btn btn-primary"data-toggle="modal"data-target="#myModal"><inputid="btnAdd"type="button"value="新建订单2"class="btn btn-primary"></div></div><!-- 新建订单1 - 对话框 --><divclass="modal fade"id="myModal"tabindex="-1"role="dialog"aria-labelledby="myModalLabel"><divclass="modal-dialog"role="document"><divclass="modal-content"><divclass="modal-header"><buttontype="button"class="close"data-dismiss="modal"aria-label="Close"><spanaria-hidden="true">×</span></button><h4class="modal-title"id="myModalLabel">Modal title</h4></div><divclass="modal-body">
- ...
- </div><divclass="modal-footer"><buttontype="button"class="btn btn-default"data-dismiss="modal">Close</button><buttontype="button"class="btn btn-primary">Save changes</button></div></div></div></div>
- {% endblock %}
- {% block script %}
- <scripttype="text/javascript">$(function(){bindBtnAddEvent();})functionbindBtnAddEvent(){$("#btnAdd").click(function(){$("#myModal").modal('show');});}</script>
- {% endblock %}
复制代码 弹框中内容
order.py
order.html
js
order.py
order_add
特殊数据输入
订单编号
负责人为当前登录
对话框u化
删除
实现点击删除按钮后,弹出确认删除的弹出框,确认后再停止删除
显示出来
orderlist.html
不停止链接跳转,采用js跳转
用 js 和 ajax的方式实现数据行的删除,注意下面的id与class绑定匹配, 例如:
$(“.btn-delete”)对应HTML中的class=“btn-delete"位置
$(”#btnConfirmDelete")对应HTML中的id="btnConfirmDelete"位置
删除内容
获取要删除的id
红色的部分:
order.py
从数据库中获取数据的类型
.all()获取到的为对象组成的querryset.filter(id=uid).first()获取的是对象.filter(id=uid).values(“id”,“title”)获取的是字典dict.filter(id=uid).values_list(“id”,“title”)获取的是元组list
- 获取的是{obj1,obj2,obj3}{{'id':1,'title':'xx1'},{'id':2,'title':'xx2'},{'id':2,'titile':'xx3'}}
- queryset = models.Order.objects.all()
- 获取的是obj1对象 {'id':1,'title':'xx1'}
- row_object = models.Order.objects.filter(id=uid).first()
- 可以拿到数据
- row_object.id1
- row_object.title xx1
- 获取的是字典dict{'id':1,'title':'xx1'}
- row_dict = models.Order.objects.filter(id=uid).values("id","title")
- 获取的是元组list[('id':1),('title':'xx1')]
- row_dict = models.Order.objects.filter(id=uid).values_list("id","title")
复制代码 编辑
显示出来
直接使用添加数据的对话框
问题:编辑需要对话框中有原来的默认数据
处置:
效果:
修改内容
思路:复用之前任务添加的代码
可行性:
编辑用户时,有名称,价格,状态+编辑用户的id
而增加用户只要名称,价格,状态三个手动输入的数据,
在后端.py中判断id是否为undefine来停止操作
假设是,添加订单号和管理员添加到数据库
不是,则将form表单传过来的数据修改到到该id所在行中
完好代码
.py- # author : Sun; time : 2023/2/11 18:11;import json
- from django.shortcuts import render, HttpResponse
- from django.http import JsonResponse
- from bm01 import models
- from bm01.utils.pagination import Pagination
- from bm01.utils.form import BootStrapModelForm
- from django.views.decorators.csrf import csrf_exempt
- from datetime import datetime
- import random
- classOrderModelForm(BootStrapModelForm):classMeta:
- model = models.Order
- # fields = "__all__"
- exclude =["oid","admin"]deforder_list(request):
- form = OrderModelForm()# 搜索框
- data_dict ={}
- search_data = request.GET.get('se',"")if search_data:
- data_dict ={"title__contains": search_data}
- queryset = models.Order.objects.filter(**data_dict).order_by("-id")# 分页 页码跳转框
- page_obj = Pagination(request, queryset)
- context ={"search_data": search_data,"form": form,"ulist": page_obj.page_queryset,"page_string": page_obj.html()}return render(request,'order_list.html', context)deforder_del(request):
- uid = request.GET.get('uid')if models.Order.objects.filter(id=uid).exists():
- models.Order.objects.filter(id=uid).delete()return JsonResponse({"status":True})return JsonResponse({"status":False,"error":"删除失败, 数据不存在,请刷新页面后重试!"})deforder_detail(request):
- uid = request.GET.get('uid')
- row_dict = models.Order.objects.filter(id=uid).values("title","price","status").first()ifnot row_dict:return JsonResponse({"status":False,"error":"数据不存在,请刷新页面后重试!"})
- result ={"status":True,"data": row_dict,}return JsonResponse(result)@csrf_exemptdeforder_add(request):'''新建/order编辑订单'''
- order = request.POST['order']if order !='undefined':
- o_obj = models.Order.objects.filter(id=order).first()
- form = OrderModelForm(data=request.POST, instance=o_obj)if form.is_valid():
- form.save()return JsonResponse({"status":True})return HttpResponse(json.dumps({"status":False,"error": form.errors}))else:
- 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 HttpResponse(json.dumps({"status":False,"error": form.errors}))
复制代码 .html- {% extends 'xlayout.html' %}
- {% block mbname %}
- <div><divclass="container"><divclass="row cle"style="margin-bottom: 20px"><divclass="col-xs-8"><ahref="#"type="button"class="btn btn-success"id="btnAdd">新建订单</a></div><divclass="col-xs-4"><formmethod="get"><divclass="input-group"><inputclass="form-control"name="se"type="text"placeholder="Search for..."value="{{ search_data }}"><spanclass="input-group-btn"><buttonclass="btn btn-default"type="submit">search number</button></span></div></form></div></div><divclass="bs-example"data-example-id="panel-without-body-with-table"><divclass="panel panel-default"><!-- Default panel contents --><divclass="panel-heading"><spanclass="glyphicon glyphicon-list"aria-hidden="true"></span> 部门列表
- </div><!-- Table --><tableclass="table table-bordered"><thead><tr><th>ID</th><th>订单号</th><th>名称</th><th>价格</th><th>状态</th><th>管理员</th><th>操作</th></tr></thead><tbody>
- {% for i in ulist %}
- <truid= {{i.id}}><td>{{ i.id }}</td><td>{{ i.oid }}</td><td>{{ i.title }}</td><td>{{ i.price }}</td><td>{{ i.get_status_display }}</td><td>{{ i.admin.username }}</td><td><buttonuid="{{ i.id }}"class="btn btn-primary btn-xs btn-edit">编辑</button><buttonuid="{{ i.id }}"class="btn btn-danger btn-xs btn-delete">删除</button></td></tr>
- {% endfor %}
- </tbody></table></div></div><ulclass="pagination">
- {{ page_string }}
- </ul><!-- 新建/编辑 订单的对话框 --><divclass="modal fade"id="myModal"tabindex="-1"role="dialog"aria-labelledby="myModalLabel"><divclass="modal-dialog"role="document"><divclass="modal-content"><divclass="modal-header"><buttontype="button"class="close"data-dismiss="modal"aria-label="Close"><spanaria-hidden="true">×</span></button><h4class="modal-title"id="myModalLabel">新见订单</h4></div><divclass="modal-body"><divclass="panel-body"><formmethod="post"id="formAdd"novalidate><div>
- {% for item in form %}
- <divclass="col-xs-10"><divclass="form-group"style="position: relative;margin-top: 20px"><label>{{ item.label }}</label>
- {{ item }}
- <spanclass="error_msg"style="color:red;position: absolute"></span></div></div>
- {% endfor %}
- </div></form></div></div></div><divclass="modal-footer"><buttontype="button"class="btn btn-default"data-dismiss="modal">取消</button><buttonid="btnSave"type="submit"class="btn btn-primary">保管</button></div></div></div><!-- 删除的对话框 --><divclass="modal fade"id="deleteModal"tabindex="-1"role="dialog"aria-labelledby="myModalLabel"><divclass="modal-dialog"role="document"><divclass="alert alert-danger alert-dismissible fade in"role="alert"><buttontype="button"class="close"data-dismiss="alert"aria-label="Close"><spanaria-hidden="true">×</span></button><h4>删除信息!</h4><pstyle="margin:10px 0;">删除后关联的数据将会一起被删除</p><pstyle="text-align: right"><buttonid="btnConfirmDelete"class="btn btn-danger">确定删除</button><buttonclass="btn btn-default"data-dismiss="modal">取消</button></p></div></div></div></div></div>
- {% endblock %}
- {% block js %}
- <scripttype="text/javascript">letDELETE_ID;letEDIT_ID;$(function(){bindBtnAddEvent();bindBtnSaveEvent();bindBtndeleteEvent();bindBtnConfirmDeleteEvent();bindBtnEditEvent();})functionbindBtnAddEvent(){$('#btnAdd').click(function(){//将正在编辑的id设置为空EDIT_ID=undefined;//改title$("#myModalLabel").text("新建订单")// 每次翻开清空对话框中上一次输入的信息$("#formAdd")[0].reset();//点击新建按钮,显示对话框$('#myModal').modal('show')})}functionbindBtnSaveEvent(){{#向后台发送ajax恳求#}$("#btnSave").click(function(){{#点击之前,清空内容#}$(".error_msg").empty();
- $.ajax({url:"/order/add/",type:"POST",data:$("#formAdd").serialize()+"&order="+EDIT_ID,dataType:"JSON",success:function(res){if(res.status){{#alert("tscg!");#}// 每次翻开清空对话框中上一次输入的信息$("#formAdd")[0].reset();// 关闭对话框$("#myModal").modal('hide');//刷新展示列表
- location.reload();}else{{#把错误信息显示在span框中#}
- $.each(res.error,function(name, errorlist){$("#id_"+ name).next().text(errorlist[0]);})}}})})}//弹出删除框functionbindBtndeleteEvent(){$(".btn-delete").click(function(){$("#deleteModal").modal('show');//获得删除的idDELETE_ID=$(this).attr('uid');});}//删除内容functionbindBtnConfirmDeleteEvent(){$("#btnConfirmDelete").click(function(){
- $.ajax({url:"/order/delete/",type:"GET",dataType:"JSON",data:{"uid":DELETE_ID},success:function(res){if(res.status){// alert("删除胜利!");// //隐藏删除框// $("#deleteModal").modal("hide");// //删除内容// $("tr[uid= '" + DELETE_ID + "']").remove();// //删除id置空// DELETE_ID = 0;
- location.reload();}else{alert(res.error);$("#deleteModal").modal("hide");DELETE_ID=0;}}})})}functionbindBtnEditEvent(){$(".btn-edit").click(function(){// 每次翻开清空对话框中上一次输入的信息$("#formAdd")[0].reset();//获得要编辑的idEDIT_ID=$(this).attr("uid")//发送ajax恳求去厚度按获得当前行相关数据
- $.ajax({url:"/order/detail/",type:"GET",dataType:"JSON",data:{"uid":EDIT_ID,},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);$("#myModal").modal("hide");
- location.reload();}}})})}</script>
- {% endblock %}
复制代码 |