# 1. 依赖bootstrap.py -ModelForm
# 2. 依赖pagemtion.py -分页
1. 创建订单管理表
class Bill(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)
# python manage.py makemigrations
# python manage.py migrate
2. 创建路由(url)
from bbc_list.views import login, home_page, order, phone, admin, task, bill
urlpatterns = [
# 订单管理
path("bill/list/", bill.bill_list),
path("bill/add/", bill.bill_add),
path("bill/delete/", bill.bill_delete),
path("bill/detail/", bill.bill_detail),
path("bill/edit/", bill.bill_edit)]
3. 创建视图函数(views-bill.py)
from datetime import datetime
import random
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from bbc_list import models
from bbc_list.utils.bootstrap import BootStrapModelForm
from bbc_list.utils.pagemtion import Pagination
# 弹窗创建订单
class BillModelForm(BootStrapModelForm):
class Meta:
model = models.Bill
# fields ="__all__"
# fields=[""]
exclude = ["oid", "admin"] # 排除某个字段
def bill_list(request):
"""订单管理列表"""
queryset = models.Bill.objects.all().order_by("-id")
page_object = Pagination(request, queryset)
form = BillModelForm()
context = {
"form": form,
"queryset": page_object.page_queryset, # 分完页的数据
"page_string": page_object.html() # 生成页面
}
return render(request, "bill_list.html", context)
@csrf_exempt
def bill_add(request):
"""新建Ajax请求"""
form = BillModelForm(data=request.POST)
# print("request.POST,", request.POST)
if form.is_valid():
# title=? price=? status=? admin_id=?
# oid
# print(form.cleaned_data)
# 订单号: 在保存数据库之前,额外增加一些不是用户输入的值(自己计算出来)
form.instance.oid = datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(1000, 9999))
# 固定设置管理员ID去哪里获取?
# request.session["info"]["id"]
# form.instance.admin_id= 当前登陆系统管理员的id
form.instance.admin_id = request.session["info"]["id"]
# 保存到数据库中
form.save()
return JsonResponse({"status": True})
return JsonResponse({"status": False, "error": form.errors})
def bill_delete(request):
"""删除订单"""
uid = request.GET.get("uid")
exists = models.Bill.objects.filter(id=uid).exists
if not exists:
return JsonResponse({"status": False, "error": "删除失败,订单不存在"})
models.Bill.objects.filter(id=uid).delete()
return JsonResponse({"status": True})
def bill_detail(request):
"""编辑"""
"""根据id获取订单信息"""
# 方式一:
"""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(result)"""
# 方式二:
uid = request.GET.get("uid")
row_dict = models.Bill.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 bill_edit(request):
"""编辑订单"""
uid = request.GET.get("uid")
row_object = models.Bill.objects.filter(id=uid).first()
if not row_object:
return JsonResponse({"status": False, "tips": "数据不存在"})
form = BillModelForm(data=request.POST, instance=row_object)
if form.is_valid():
form.save()
return JsonResponse({"status": True})
return JsonResponse({"status": False, "error": form.errors})
4. 创建html页面(bill_list.html)
{% extends "one.html" %}
{% block content %}
<div class="container">
<div style="margin-bottom:10px;">
<!-- modelForm:这种方式和绑定id一样,可以弹出对话框 -->
<input type="button" value="新建订单1" class="btn btn-success" data-toggle="modal" data-target="#myModal">
<input id="btnAdd" type="button" value="新建订单2" class="btn btn-success">
</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>
<ul class="pagination">
{{ page_string }}
</ul>
</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">
<!--style="position: relative: 相对定位; position: absolute:绝对定位-->
<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>
<!-- 加上 data-dismiss="modal" 就可以取消对话框-->
<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(); // 新建
bingBtnSavaEvent(); //保存
bingBtnDeleteEvent(); //删除
bingBtnConfirmDeleteEvent(); //确认删除
bingBtnEditEvent(); //编辑
})
function bindBtnAddEvent(){
$("#btnAdd").click(function(){
//将正在编辑的id置空
EDIT_ID=undefined;
//清空对话框内容
$("#formAdd")[0].reset();
//设置对话框标题
$("#myModalLabel").text("新建");
//点击新建按钮,显示对话框
$("#myModal").modal("show");
});
}
function bingBtnSavaEvent(){
$("#btnSave").click(function(){
//点击后,发送ajax请求
//清除错误信息
$(".error-msg").empty();
//进行判断: 新建 or 编辑
if(EDIT_ID){
//编辑
doEdit();
}else{
//添加
doAdd();
}
})
}
function doEdit(){
$.ajax({
url: '/bill/edit/'+'?uid='+EDIT_ID, // order/edit/?uid=1
type:"post",
data: $("#formAdd").serialize(),
dataType:"JSON",
success: function(res){
console.log(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({
url:"/bill/add/",
type:"post",
data:$("#formAdd").serialize(),
dataType:"JSON",
success:function(res){
console.log(res);
if(res.status){
//alert("创建成功")
//清空表单,$('#formAdd')是jQuery对象, ('#formAdd')[0]:DOM对象;
$("#formAdd")[0].reset();
//关闭对话框
$("#myModel").modal("hide");
//刷新页面
location.reload();
}else{
//把错误信息显示在对话框中
$.each(res.error,function(name,errorList){
$("#id_"+name).next().text(errorList[0]);
})
}
}
})
}
function bingBtnDeleteEvent(){
$(".btn-delete").click(function(){
// alert("点击了删除");
//显示删除对话框
$("#deleteModal").modal("show");
//获取当前行的ID并赋值给全局变量 attr: 该方法可以设置或返回被选元素的属性值
DELETE_ID=$(this).attr('uid');
})
}
// 确认删除
function bingBtnConfirmDeleteEvent(){
$("#btnConfirmDelete").click(function(){
//点击确认删除按钮,将全局变量中设置的那个要删除的id发送到后台
$.ajax({
url:"/bill/delete/", // /bill/delete?uid=11
type:"GET",
data:{
uid:DELETE_ID
},
dataType:"JSON",
success: function(res){
if(res.status){
// alert("删除成功")
//第一种: 隐藏删除框
//$("#deleteModal").modal("hide");
//在页面上将当前一行数据删除JS,找到tr标签并且uid是delete_id
// $("tr[uid='"+DELETE_ID+"']").remove();
//将全局变量-要删除的ID置空
// DELETE_ID=0;
// 第二种: 简单的思路:直接刷新页面
location.reload();
}else{
//删除失败
alert(res.error)
}
}
})
})
}
function bingBtnEditEvent(){
$('.btn-edit').click(function(){
//清空对话框内容
$("#formAdd")[0].reset();
// 获取当前行的ID并赋值给全局变量 attr: 该方法可以设置或返回被选元素的属性值
var uid=$(this).attr("uid");
EDIT_ID=uid;
// 发送Ajax请求去获取当前行的相关数据 /bill/detail?uid=12
$.ajax({
url:"/bill/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 %}
标签:实战,status,13,uid,function,res,bill,订单,id
From: https://www.cnblogs.com/kh-1314/p/17057375.html