Model建表
Model建表
# 积分订单表
class Order(models.Model):
order_id = models.CharField(verbose_name="订单号", max_length=64)
user = models.ForeignKey(verbose_name="用户名", to="UserInfo", to_field="name", on_delete=models.CASCADE)
product = models.ForeignKey(verbose_name="商品名称", to="Product", to_field="id", on_delete=models.CASCADE)
order_choices = (
(1, "待处理"),
(2, "已发货"),
(3, "已完成"),
(4, "已取消"),
)
address = models.ForeignKey(verbose_name="地址Id", to="Address", to_field="id", on_delete=models.CASCADE, null=True,
default=1)
state = models.SmallIntegerField(verbose_name="订单状态", choices=order_choices, default=1)
redeem_time = models.DateTimeField(auto_now_add=True)
def get_state_color(self):
"""
获取当前订单状态对应的 Bootstrap 标签颜色。
"""
if self.state == 1:
return 'warning'
elif self.state == 2:
return 'info'
elif self.state == 3:
return 'success'
elif self.state == 4:
return 'danger'
else:
return 'default'
urls路径编写
urls路径编写
# 司机信息表(后台)
path("driver/list/", driver.driver_list),
path('driver/add/', driver.driver_add),
path('driver/delete/', driver.driver_delete),
path('driver/detail/', driver.driver_detail),
path('driver/edit/', driver.driver_edit),
html编写
html编写
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>司机信息管理</title>
</head>
<body>
{% extends 'layout.html' %}
{% block content %}
<div class="container">
<div style="margin-bottom: 20px">
<button id="btnAdd" type="button" class="btn btn-success">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
新建司机信息
</button>
<div style="float: right;width: 300px;">
<form method="get">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="按名字搜索"
value="{{ search_data }}">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
</button>
</span>
</div>
</form>
</div>
</div>
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<span class="glyphicon glyphicon-list" aria-hidden="true"></span> 地址列表
</div>
<!-- Table -->
<table class="table table-hover">
<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>
<th>{{ obj.id }}</th>
<td>{{ obj.name }}</td>
<td>{{ obj.phone }}</td>
<td>{{ obj.get_license_type_display }}</td>
<td>{{ obj.hire_date }}</td>
<td>{{ obj.get_gender_display }}</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">
{{ 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请求)
$.ajax({
url: "/driver/edit/" + "?uid=" + EDIT_ID, // -> /order/edit/?uid=12
type: "post",
data: $("#formAdd").serialize(),
dataType: "JSON",
success: function (res) {
if (res.status) {
// 清空表单 $("#formAdd")是jQuery对象 -> $("#formAdd")[0] DOM对象
$("#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请求)
$.ajax({
url: "/driver/add/",
type: "post",
data: $("#formAdd").serialize(),
dataType: "JSON",
success: function (res) {
if (res.status) {
// alert("创建成功");
// 清空表单 $("#formAdd")是jQuery对象 -> $("#formAdd")[0] DOM对象
$("#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 () {
$.ajax({
url: "/driver/delete/", // => /order/delete/?uid=123
type: "GET",
data: {
uid: DELETE_ID
},
dataType: "JSON",
success: function (res) {
if (res.status) {
// 隐藏删除框
// $("#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去后端获取当前行的相关数据 /order/detail/?uid=123
$.ajax({
url: "/driver/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 %}
From编写(折叠块)
From编写
class DriverModelForm(BootStrapModelForm):
class Meta:
model = models.DriverInfo
fields = "__all__"
# exclude = ["user"]
后端编写
后端编写
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from app01.utils.form import *
from app01.utils.pagination import Pagination
DriverInfo
DriverModelForm
name 搜索
html
def driver_list(request):
# 构造搜索
data_dict = {}
search_data = request.GET.get('q', "")
if search_data:
data_dict["name__contains"] = search_data
# 根据搜索条件去数据库获取
queryset = models.DriverInfo.objects.filter(**data_dict)
# 分页
page_object = Pagination(request, queryset)
form = DriverModelForm()
context = {
'form': form,
'queryset': page_object.page_queryset,
'page_string': page_object.html(),
"search_data": search_data
}
return render(request, 'driver_list.html', context)
@csrf_exempt
def driver_add(request):
""" 新建订单(Ajax请求)"""
form = DriverModelForm(data=request.POST)
if form.is_valid():
form.save()
return JsonResponse({"status": True})
return JsonResponse({"status": False, 'error': form.errors})
def driver_delete(request):
""" 删除订单 """
uid = request.GET.get('uid')
exists = models.DriverInfo.objects.filter(id=uid).exists()
if not exists:
return JsonResponse({"status": False, 'error': "删除失败,数据不存在。"})
models.DriverInfo.objects.filter(id=uid).delete()
return JsonResponse({"status": True})
def driver_detail(request):
""" 根据ID详细 """
uid = request.GET.get("uid")
row_dict = models.DriverInfo.objects.filter(id=uid).values().first()
if not row_dict:
return JsonResponse({"status": False, 'error': "数据不存在。"})
# 从数据库中获取到一个对象 row_object
result = {
"status": True,
"data": row_dict
}
return JsonResponse(result)
@csrf_exempt
def driver_edit(request):
""" 编辑 """
uid = request.GET.get("uid")
row_object = models.DriverInfo.objects.filter(id=uid).first()
if not row_object:
return JsonResponse({"status": False, 'tips': "数据不存在,请刷新重试。"})
form = DriverModelForm(data=request.POST, instance=row_object)
if form.is_valid():
form.save()
return JsonResponse({"status": True})
return JsonResponse({"status": False, 'error': form.errors})