启动项目命令
python manage.py runserver
取消模态框功能
js实现列表数据删除
第二种实现思路
使用jquery修改模态框标题
编辑页面拿到数据库数据显示默认数据功能实现
想要去数据库中获取数据时:对象/字典
三种不同的数据类型
使用Ajax传入数据实现表单编辑,删除,修改功能
order1.py
import json
import random
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from app01 import models
from app01.utils.bootstrap import BootStrapModelForm
from django.views.decorators.csrf import csrf_exempt
from datetime import datetime
from app01.utils.pagination import Pagination
class OrderModelForm(BootStrapModelForm):
class Meta:
model = models.Order
# field = "__all__"
# fields = [""]
exclude = ["oid", "admin"]
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)
@csrf_exempt
def order_add(request):
""" 新建订单 (Ajax请求)"""
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))
# 固定设置管理员ID
# form.instance.admin = 当前登录系统管理员的ID
# keys = list(request.session.keys())
# print(keys)
form.instance.admin_id = request.session["info"]["id"]
# 保存到数据库中
form.save()
return JsonResponse({"status": True})
# return HttpResponse(json.dumps({"status": True}))
return JsonResponse({"status": False, 'error': form.errors})
def order_delete(request):
""" 删除订单 """
uid = request.GET.get("uid")
exists = models.Order.objects.filter(id=uid).exists()
if not exists:
return JsonResponse({"status": True, 'error': "删除失败,数据不存在"})
models.Order.objects.filter(id=uid).delete()
return JsonResponse({"status": True})
def order_detail(request):
""" 根据ID获取订单明细 """
# 方式1
# uid = request.GET.get("uid")
# row_object = models.Order.objects.filter(id=uid).first()
# if not row_object:
# return JsonResponse({"status": False, 'error': "数据不存在,"})
#
# # 从数据库中获取到一个对象 row_object
# result = {
# "status": True,
# "data": {
# "title": row_object.title,
# "price": row_object.price,
# "status": row_object.status,
# }
# }
# return JsonResponse({"status": True, "data": result})
# 方式2
uid = request.GET.get("uid")
row_dict = models.Order.objects.filter(id=uid).values("title", "price", "status").first()
if not row_dict:
return JsonResponse({"status": False, "error": "数据不存在。"})
# 从数据库中获取到一个对象 row_object
result = {
"status": True,
"data": row_dict
}
return JsonResponse(result)
@csrf_exempt
def order_edit(request):
""" 编辑订单 """
uid = request.GET.get("uid")
row_object = models.Order.objects.filter(id=uid).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})
return JsonResponse({"status": False, "error": form.errors})
order_list.html
{% extends 'layout.html' %}
{% block content %}
<div class="container">
<div style="margin-bottom: 10px">
<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 class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
订单列表
</div>
<!-- Table -->
<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 %}
<tr uid="{{ obj.id }}">
<th>{{ obj.id }}</th>
<td>{{ obj.oid }}</td>
<td>{{ obj.title }}</td>
<td>{{ obj.price }}</td>
<td>{{ obj.get_status_display }}</td>
<td>{{ obj.admin.username }}</td>
<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>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="clearfix">
<ul class="pagination" style="float:left;">
{{ page_string }}
</ul>
</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="formAdd">
<div class="clearfix">
{% for field in form %}
<div class="col-xs-6">
<div class="form-group" style="position: relative;margin-bottom: 20px;">
<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">
<h4>是否确定删除?</h4>
<p style="margin: 10px 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>
{% endblock %}
{% block js %}
<script type="text/javascript">
var DELETE_ID;
var EDIT_ID;
$(function () {
bindBtnAddEvent();
bindBtnSaveEvent();
bindBtnDeleteEvent();
bindBtnConfirmDeleteEvent();
bindBtnEditEvent();
})
function bindBtnAddEvent() {
$("#btnAdd").click(function () {
//将正在编辑的ID设置为空
EDIT_ID = undefined;
//清空对话框中的数据
$("#formAdd")[0].reset();
//设置对话框的标题
$("#myModalLabel").text("新建");
//点击新建按钮,显示对话框
$('#myModal').modal('show')
});
}
function bindBtnSaveEvent() {
$("#btnSave").click(function() {
// 清除错误信息
$("#error-msg").empty();
if(EDIT_ID) {
//编辑
doEdit();
} else {
//添加
doAdd();
}
});
}
function doEdit() {
// 向后台发送请求
$.ajax({
url: "/order/edit/" + "?uid=" + EDIT_ID,
type: "post",
data: $("#formAdd").serialize(),
dataType: "JSON",
success: function (res) {
if(res.status) {
alert("修改成功");
// 清空表单
$("#formAdd")[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: $("#formAdd").serialize(),
dataType: "JSON",
success: function (res) {
if(res.status) {
alert("创建成功");
// 清空表单
$("#formAdd")[0].reset();
//关闭对话框
$('#myModal').modal('hide');
location.reload();
} else {
$.each(res.error, function (name, errorList) {
$("#id_" + name).next().text(errorList[0]);
})
}
}
});
}
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){
<!-- //alert("删除成功");-->
<!-- //隐藏删除框-->
<!-- $("deleteModal").modal('hide');-->
<!-- //在页面上将当前一行数据删除(js)-->
<!-- $("tr[uid='" + DELETE_ID + "']").remove();-->
<!-- //要删除的ID置空-->
<!-- DELETE_ID = 0;-->
//简单的实现思路
location.reload();
}else{
//删除失败
alert(res.error);
}
}
})
});
}
function bindBtnEditEvent() {
$(".btn-edit").click(function () {
//清空对话框中的数据
$("#formAdd")[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);
}
}
})
});
}
</script>
{% endblock %}
导入echarts图表
出现图表加载不出来的问题
可能是
<script src="https://cdn.jsdelivr.net/npm/echarts@5.5.1/dist/echarts.min.js"></script>
放在了
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('m1'));
// 指定图表的配置项和数据
var option = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data: ['销量']
},
xAxis: {
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
},
yAxis: {},
series: [
{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}
]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
的后面了
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » Django学习第六天
发表评论 取消回复