【Django】网上蛋糕商城后台-商品管理

1.商品管理功能

当管理员点击商品管理时,发送服务器请求

path('admin/goods_list/', viewsAdmin.goods_list),
# 处理商品列表请求
def goods_list(request):
    try:
        type = request.GET["type"]
    except:
        type = 0
    try:
        ym = request.GET["ym"]
    except:
        ym = 1
    if int(type) == 0:
        goodsList = Goods.objects.all().order_by("-id").values()
        for goods in goodsList:
            typeName = Type.objects.get(id=goods["type_id"]).name
            types = Recommend.objects.filter(goods_id=goods["id"]).values_list("type")
            if (1,) in types:
                goods["isScroll"] = True
            if (2,) in types:
                goods["isHot"] = True
            if (3,) in types:
                goods["isNew"] = True
            goods["typeName"] = typeName

    else:
        recommends = Recommend.objects.filter(type=type).order_by("-goods_id")
        goodsList = []
        for r in recommends:
            # 根据推荐栏类型查询商品信息,将查询的对象转换成字典
            goods = Goods.objects.get(id=r.goods_id).__dict__
            # 根据商品id查询该商品添加在哪些推荐栏中
            types = Recommend.objects.filter(goods_id=r.goods_id).values_list("type")
            if (1,) in types:
                goods["isScroll"] = True
            if (2,) in types:
                goods["isHot"] = True
            if (3,) in types:
                goods["isNew"] = True
            # 根据商品中的分类id查询分类名称
            typeName = Type.objects.get(id=goods["type_id"])
            goods["typeName"] = typeName.name
            goodsList.append(goods)
    # 将该分类的商品信息进行分页处理,每页显示6条记录
    pag = paginator.Paginator(goodsList, 6)
    # 根据当前页码获取当前分页信息
    pageInfo = pag.get_page(ym)
    # 获取当前页的商品列表信息
    goodsList = pageInfo.object_list
    # 获取总页码数
    yms = pag.page_range
    return render(request, "adminTemp/goods_list.html",
                  {"goodsList": goodsList, "page": pageInfo, "yms": yms, "type": type})
<!DOCTYPE html>
<html>
<head>
    <title>商品列表</title>
    {% load static %}
    <meta charset="utf-8"/>
    <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"/>
    <link rel="stylesheet" href="{% static 'css/page.css' %}"/>
</head>
<body>
<div class="container-fluid">
    {% include "adminTemp/header.html" %}
    <div class="text-right"><a class="btn btn-warning" href="/admin/goods_add/">添加商品</a></div>
    <br>
    <ul role="tablist" class="nav nav-tabs">

        <li {% if type == 0 %}
            class="active"
        {% endif %} role="presentation"><a href="/admin/goods_list/">全部商品</a></li>
        <li {% if type == 1 %}
            class="active"
        {% endif %} role="presentation"><a href="/admin/goods_list/?type=1">条幅推荐</a></li>
        <li {% if type == 2 %}
            class="active"
        {% endif %} role="presentation"><a href="/admin/goods_list/?type=2">热销推荐</a></li>
        <li {% if type == 3 %}
            class="active"
        {% endif %} role="presentation"><a href="/admin/goods_list/?type=3">新品推荐</a></li>
    </ul>
    <br>
    <table class="table table-bordered table-hover">
        <tr>
            <th width="5%">ID</th>
            <th width="10%">图片</th>
            <th width="10%">名称</th>
            <th width="20%">介绍</th>
            <th width="10%">价格</th>
            <th width="10%">类目</th>
            <th width="25%">操作</th>
        </tr>
        {% for g in goodsList %}
            <tr>
                <td><p>{{ g.id }}</p></td>
                <td><p><a href="/goods_detail/?id={{ g.id }}" target="_blank"><img src="{% static g.cover %}"
                                                                                   width="100px"
                                                                                   height="100px"></a></p></td>
                <td><p><a href="/goods_detail/?id={{ g.id }}" target="_blank">{{ g.name }}</a></p></td>
                <td><p>{{ g.intro }}</p></td>
                <td><p>{{ g.price }}</p></td>
                <td><p>{{ g.typeName }}</p></td>
                <td>
                    <p>
                        {% if g.isScroll %}
                            <a class="btn btn-info"
                               href="/admin/goods_recommend/?id={{ g.id }}&method=remove&typeTarget=1">移出条幅</a>
                        {% endif %}
                        {% if not g.isScroll %}
                            <a class="btn btn-primary"
                               href="/admin/goods_recommend/?id={{ g.id }}&method=add&typeTarget=1">加入条幅</a>
                        {% endif %}
                        {% if g.isHot %}
                            <a class="btn btn-info"
                               href="/admin/goods_recommend/?id={{ g.id }}&method=remove&typeTarget=2">移出热销</a>
                        {% endif %}
                        {% if not g.isHot %}
                            <a class="btn btn-primary"
                               href="/admin/goods_recommend/?id={{ g.id }}&method=add&typeTarget=2">加入热销</a>
                        {% endif %}
                        {% if g.isNew %}
                            <a class="btn btn-info"
                               href="/admin/goods_recommend/?id={{ g.id }}&method=remove&typeTarget=3">移出新品</a>
                        {% endif %}
                        {% if not g.isNew %}
                            <a class="btn btn-primary"
                               href="/admin/goods_recommend/?id={{ g.id }}&method=add&typeTarget=3">加入新品</a>
                        {% endif %}
                    </p>
                    <a class="btn btn-success"
                       href="/admin/goods_editshow/?id={{ g.id  }}&ym={{ page.number  }}">修改</a>
                    <a class="btn btn-danger"
                       href="/admin/goods_delete/?id={{ g.id  }}&ym={{ page.number  }}">删除</a>
                </td>
            </tr>
        {% endfor %}
    </table>
    <br>
    <!-- 显示页码导航栏 -->
    <div id="nav" align="center">
        <!-- 上一页 -->
        <!-- 判断当前页是否有上一页,如果有上一页则显示上一页的按钮,否则就不显示上一页 -->
        {% if page.has_previous %}
            <a href="/admin/goods_list/?ym={{ page.previous_page_number }}&type={{ type }}" class="up_page">上一页</a>
        {% endif %}
        <!-- 页码 -->
        {% for ym in yms %}
            {% if page.number == ym %}
                <a href="/admin/goods_list/?ym={{ ym }}&type={{ type }}" class="p_page c_page">{{ ym }}</a>
            {% else %}
                <a href="/admin/goods_list/?ym={{ ym }}&type={{ type }}" class="p_page">{{ ym }}</a>
            {% endif %}
        {% endfor %}

        <!-- 下一页 -->
        {% if page.has_next %}
            <a href="/admin/goods_list/?ym={{ page.next_page_number }}&type={{ type }}" class="do_page">下一页</a>
        {% endif %}
    </div>
    <br>
</div>
</body>
</html>

2.加入或移除推荐栏功能

选择某个商品,点击加入条幅,移除条幅,加入热销,移除热销,加入新品,移除新品按钮时,触发请求事件,传递不同参数信息给服务器

path('admin/goods_recommend/',viewsAdmin.goods_recommend),
# 处理商品的推荐栏请求
def goods_recommend(request):
    id = request.GET["id"]
    method = request.GET["method"]
    typeTarget = request.GET["typeTarget"]
    if "add" == method:
        # 添加至推荐栏
        Recommend.objects.create(goods_id=id, type=typeTarget)
    elif "remove" == method:
        # 从推荐栏中移除
        r = Recommend.objects.get(goods_id=id, type=typeTarget)
        r.delete()
    # 刷新商品管理列表页面
    return redirect(goods_list)

3.添加商品功能

当管理员点击添加商品按钮,触发请求事件

path('admin/goods_add/', viewsAdmin.goods_add),
# 处理添加商品页面的跳转请求
def goods_add(request):
    types = Type.objects.all()
    return render(request, "adminTemp/goods_add.html", {"typeList": types})
<!DOCTYPE html>
<html>
<head>
    <title>商品添加</title>
    {% load static %}
    <meta charset="utf-8"/>
    <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"/>
</head>
<body>
<div class="container-fluid">
    {% include "adminTemp/header.html" %}
    <br><br>
    <form class="form-horizontal" action="/admin/addGoods/" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <div class="form-group">
            <label for="input_name" class="col-sm-1 control-label">名称</label>
            <div class="col-sm-6">
                <input type="text" class="form-control" id="input_name" name="name" required="required">
            </div>
        </div>
        <div class="form-group">
            <label for="input_name" class="col-sm-1 control-label">价格</label>
            <div class="col-sm-6">
                <input type="text" class="form-control" id="input_name" name="price">
            </div>
        </div>
        <div class="form-group">
            <label for="input_name" class="col-sm-1 control-label">介绍</label>
            <div class="col-sm-6">
                <input type="text" class="form-control" id="input_name" name="intro">
            </div>
        </div>
        <div class="form-group">
            <label for="input_name" class="col-sm-1 control-label">库存</label>
            <div class="col-sm-6">
                <input type="text" class="form-control" id="input_name" name="stock">
            </div>
        </div>
        <div class="form-group">
            <label for="input_file" class="col-sm-1 control-label">封面图片</label>
            <div class="col-sm-6">
                <input type="file" name="cover" id="input_file" required="required">推荐尺寸: 500 * 500
            </div>
        </div>
        <div class="form-group">
            <label for="input_file" class="col-sm-1 control-label">详情图片1</label>
            <div class="col-sm-6">
                <input type="file" name="image1" id="input_file" required="required">推荐尺寸: 500 * 500
            </div>
        </div>
        <div class="form-group">
            <label for="input_file" class="col-sm-1 control-label">详情图片2</label>
            <div class="col-sm-6">
                <input type="file" name="image2" id="input_file" required="required">推荐尺寸: 500 * 500
            </div>
        </div>
        <div class="form-group">
            <label for="select_topic" class="col-sm-1 control-label">类目</label>
            <div class="col-sm-6">
                <select class="form-control" id="select_topic" name="typeid">
                    {% for t in typeList %}
                        <option value="{{ t.id }}">{{ t.name }}</option>
                    {% endfor %}
                </select>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-1 col-sm-10">
                <button type="submit" class="btn btn-success">提交保存</button>
            </div>
        </div>
    </form>
</div>
</body>
</html>

当管理员填写完商品信息以及选择好上传的图片后,点击提交保存按钮,将表单提交给服务器

path('admin/addGoods/',viewsAdmin.addGoods),
# 获取商品添加请求
def addGoods(request):
    name = request.POST["name"]
    price = request.POST["price"]
    intro = request.POST["intro"]
    stock = request.POST["stock"]
    pic = request.FILES.getlist('cover')
    cover = upload(pic[0])
    pic = request.FILES.getlist('image1')
    image1 = upload(pic[0])
    pic = request.FILES.getlist('image2')
    image2 = upload(pic[0])
    typeid = request.POST["typeid"]
    Goods.objects.create(name=name, price=price, intro=intro, stock=stock, cover=cover, image1=image1, image2=image2,
                         type_id=typeid)
    # 添加成功刷新商品管理列表页面
    return redirect(goods_list)

对于处理图片上传的函数如下

def upload(pic, image=None):
    # 指定文件上传路径
    path = "CookieShopClient/static/picture/"
    if image:
       file_path = path + str(image)[8:]
       # 检查文件是否存在
       if os.path.isfile(file_path):
           # 删除文件
           os.remove(file_path)
    imageName = ""
    # 检查文件夹是否存在
    if not os.path.exists(path):
        # 如果文件夹不存在,则创建它
        os.makedirs(path)
    imageName = pic.name
    # 获取当前时间的时间戳(秒)
    timestamp_seconds = time.time()
    # 转换为毫秒
    timestamp_milliseconds = int(timestamp_seconds * 1000)
    imageName = str(imageName).split(".")[0] + str(timestamp_milliseconds) + "." + str(imageName).split(".")[1]
    url = path + imageName
    with open(url, 'wb') as f:
        for data in pic.chunks():
            f.write(data)
    return "/picture/" + imageName

4.修改商品功能

当管理员选择某个商品进行修改时,将该商品的商品编号以及所在分页页码发送给修改页面

path('admin/goods_editshow/',viewsAdmin.goods_editshow),
# 处理跳转至修改页面的请求
def goods_editshow(request):
    id = request.GET["id"]
    ym = request.GET["ym"]
    goods = Goods.objects.get(id=id)
    # 查询该商品所属分类
    typeName = Type.objects.get(id=goods.type_id).name
    types = Type.objects.all()
    return render(request, "adminTemp/goods_edit.html", {"g": goods, "typeName": typeName, "ym": ym, "typeList": types})
<!DOCTYPE html>
<html>
<head>
	<title>商品编辑</title>
    {% load static %}
	<meta charset="utf-8" />
	<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}" />
</head>
<body>
<div class="container-fluid">
	{% include "adminTemp/header.html" %}
	<br><br>
	<form class="form-horizontal" action="/admin/goods_edit/" method="post" enctype="multipart/form-data">
        {% csrf_token %}
		<input type="hidden" name="id" value="{{ g.id  }}"/>
		<input type="hidden" name="cover" value="{{ g.cover  }}"/>
		<input type="hidden" name="image1" value="{{ g.image1  }}"/>
		<input type="hidden" name="image2" value="{{ g.image2  }}"/>
		<input type="hidden" name="ym" value="{{ ym  }}"/>
		<input type="hidden" name="type" value="{{ typeName }}"/>
		<div class="form-group">
			<label for="input_name" class="col-sm-1 control-label">名称</label>
			<div class="col-sm-6">
				<input type="text" class="form-control" id="input_name" name="name" value="{{ g.name  }}" required="required">
			</div>
		</div>
		<div class="form-group">
			<label for="input_name" class="col-sm-1 control-label">价格</label>
			<div class="col-sm-6">
				<input type="text" class="form-control" id="input_name" name="price" value="{{ g.price  }}">
			</div>
		</div>
		<div class="form-group">
			<label for="input_name" class="col-sm-1 control-label">介绍</label>
			<div class="col-sm-6">
				<input type="text" class="form-control" id="input_name" name="intro" value="{{ g.intro  }}">
			</div>
		</div>
		<div class="form-group">
			<label for="input_name" class="col-sm-1 control-label">库存</label>
			<div class="col-sm-6">
				<input type="text" class="form-control" id="input_name" name="stock" value="{{ g.stock  }}">
			</div>
		</div>
		<div class="form-group">
			<label for="input_file" class="col-sm-1 control-label">封面图片</label>
			<div class="col-sm-6"><img src="{% static g.cover %}" width="100" height="100"/>
				<input type="file" name="cover"  id="input_file">推荐尺寸: 500 * 500
			</div>
		</div>
		<div class="form-group">
			<label for="input_file" class="col-sm-1 control-label">详情图片1</label>
			<div class="col-sm-6"><img src="{% static g.image1 %}" width="100" height="100"/>
				<input type="file" name="image1"  id="input_file">推荐尺寸: 500 * 500
			</div>
		</div>
		<div class="form-group">
			<label for="input_file" class="col-sm-1 control-label">详情图片2</label>
			<div class="col-sm-6"><img src="{% static g.image2 %}" width="100" height="100"/>
				<input type="file" name="image2"  id="input_file">推荐尺寸: 500 * 500
			</div>
		</div>
		<div class="form-group">
			<label for="select_topic" class="col-sm-1 control-label">类目</label>
			<div class="col-sm-6">
				<select class="form-control" id="select_topic" name="typeid">
                    {% for t in typeList %}
                    <option
                        {% if t.id == g.type_id %}
                        selected="selected"
                        {% endif %}
                         value="{{ t.id }}">{{ t.name  }}</option>
                    {% endfor %}

				</select>
			</div>
		</div>
		<div class="form-group">
			<div class="col-sm-offset-1 col-sm-10">
				<button type="submit" class="btn btn-success">提交修改</button>
			</div>
		</div>
	</form>
</div>
</body>
</html>

当管理员修改信息以及重新选择新图片后,将表单提交给服务器,服务器通过比较原图片以及新图片地址判断当前图片是否需要重新上传

path('admin/goods_edit/',viewsAdmin.goods_edit),
# 处理修改商品信息的请求
def goods_edit(request):
    id = request.POST["id"]
    # 根据id查询出原商品信息
    goods = Goods.objects.filter(id=id)
    name = request.POST["name"]
    price = request.POST["price"]
    intro = request.POST["intro"]
    stock = request.POST["stock"]
    try:
        # 判断修改页面传递的图片名称是否和数据库中原本图片名称一致,如果一致表示该图片没有被修改
        # 如果图片没有修改,则返回值为空
        pic = request.FILES.getlist('cover')[0]
        cover = upload(pic, goods[0].cover)
    except:
        cover = goods[0].cover
    try:
        # 判断修改页面传递的图片名称是否和数据库中原本图片名称一致,如果一致表示该图片没有被修改
        # 如果图片没有修改,则返回值为空
        pic = request.FILES.getlist('image1')[0]
        image1 = upload(pic, goods[0].image1)
    except:
        image1 = goods[0].image1
    try:
        # 判断修改页面传递的图片名称是否和数据库中原本图片名称一致,如果一致表示该图片没有被修改
        # 如果图片没有修改,则返回值为空
        pic = request.FILES.getlist('image2')[0]
        image2 = upload(pic, goods[0].image2)
    except:
        image2 = goods[0].image2

    typeid = request.POST["typeid"]
    ym = request.POST["ym"]
    # 修改商品信息
    goods.update(name=name, price=price, intro=intro, stock=stock, cover=cover, image1=image1, image2=image2,
                 type_id=typeid)
    return HttpResponseRedirect("/admin/goods_list/?ym=" + ym)

5.删除商品功能

当管理员选择某个商品删除的时候,触发请求

path('admin/goods_delete/',viewsAdmin.goods_delete),
# 处理删除商品的请求
def goods_delete(request):
    id=request.GET["id"]
    ym=request.GET["ym"]
    # 先查看当前商品是否有被添加为推荐栏商品,如果有,需要先从推荐栏中删除
    rs=Recommend.objects.filter(goods_id=id)
    if rs:
        rs.delete()
    # 根据商品编号将商品信息查询出来
    goods=Goods.objects.get(id=id)
    remove_image(goods.cover)
    remove_image(goods.image1)
    remove_image(goods.image2)
    goods.delete()
    return HttpResponseRedirect("/admin/goods_list/?ym=" + ym)
上一篇:(二)C++之类与对象-三.常成员、常对象


下一篇:单例设计模式