国庆手撸商品管理系统(三)

国庆手撸商品管理系统(三),第1张

概述`之前的内容` "点我管理系统(一)" "点我管理系统(二)" 一.实现的内容 商品退货 商品库存 商品进货 商品删除 商品还原 时钟 优化模型 二.后续内容准

之前的内容

点我管理系统(一)

点我管理系统(二)

一.实现的内容

商品退货

商品库存

商品进货

商品删除

商品还原

时钟

优化模型

二.后续内容准备优化内容把数据库查询的内容存在缓存中增加按日期,按商品名查询增加快捷商品增加优化代码优化界面三.目录结构
drf_test|___drf_API|    |___admin.py|    |___apps.py|    |___migrations|    |___models.py|    |___tests.py|    |___userinfo_form.py|    |___vIEws|    |    |____commodity.py|    |    |____user.py|    |_____init__.py|___drf_test|    |___settings.py|    |___urls.py|    |___wsgi.py|    |_____init__.py|___img|    |___avatar|___manage.py|___static|    |___bootstrap-3.3.7-dist|    |___jquery-3.4.1.min.Js|___templates|    |___aa.HTML|    |___add.HTML|    |___del.HTML|    |___index.HTML|    |___login.HTML|    |___register.HTML|    |___return.HTML|    |___sales.HTML|    |___show.HTML|    |___show_del.HTML|    |___template.HTML|_____pycache__|    |___manage.cpython-37.pyc
四.代码1.配置

setting.py

"""Django settings for drf_test project.Generated by 'django-admin startproject' using Django 1.11.22.For more information on this file,seehttps://docs.djangoproject.com/en/1.11/topics/settings/For the full List of settings and their values,seehttps://docs.djangoproject.com/en/1.11/ref/settings/"""import os# Build paths insIDe the project like this: os.path.join(BASE_DIR,...)BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))# Quick-start development settings - unsuitable for production# See https://docs.djangoproject.com/en/1.11/howto/deployment/checkList/# Security WARNING: keep the secret key used in production secret!SECRET_KEY = 'ppa5l3jvxr4k^ow*4o+0_^7@&sa3x+!hb_$artwraa%60iq@g7'# Security WARNING: don't run with deBUG turned on in production!DEBUG = TrueALLOWED_HOSTS = []# Application deFinitionINSTALLED_APPS = [    'django.contrib.admin','django.contrib.auth','django.contrib.ContentTypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','drf_API','rest_framework',]MIDDLEWARE = [    'django.mIDdleware.security.SecurityMIDdleware','django.contrib.sessions.mIDdleware.SessionMIDdleware','django.mIDdleware.common.CommonMIDdleware','django.mIDdleware.csrf.CsrfVIEwMIDdleware','django.contrib.auth.mIDdleware.AuthenticationMIDdleware','django.contrib.messages.mIDdleware.MessageMIDdleware','django.mIDdleware.clickjacking.XFrameOptionsMIDdleware',]ROOT_URLconf = 'drf_test.urls'TEMPLATES = [    {        'BACKEND': 'django.template.backends.django.DjangoTemplates','Dirs': [os.path.join(BASE_DIR,'templates')],'APP_Dirs': True,'OPTIONS': {            'context_processors': [                'django.template.context_processors.deBUG','django.template.context_processors.request','django.contrib.auth.context_processors.auth','django.contrib.messages.context_processors.messages',],},]Wsgi_APPliCATION = 'drf_test.wsgi.application'# Database# https://docs.djangoproject.com/en/1.11/ref/settings/#databasesDATABASES = {    'default': {        'ENGINE': 'django.db.backends.MysqL',# 数据库引擎        'name': 'mib',# 你要存储数据的库名,事先要创建之        'USER': 'root',# 数据库用户名        'PASSWORD': '16745',# 密码        'HOST': 'localhost',# IP        'PORT': '3306',# 数据库使用的端口    }}# Password valIDation# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-valIDatorsAUTH_PASSWORD_VALIDATORS = [    {        'name': 'django.contrib.auth.password_valIDation.UserAttributeSimilarityValIDator',{        'name': 'django.contrib.auth.password_valIDation.MinimumLengthValIDator',{        'name': 'django.contrib.auth.password_valIDation.CommonPasswordValIDator',{        'name': 'django.contrib.auth.password_valIDation.NumericPasswordValIDator',]# Internationalization# https://docs.djangoproject.com/en/1.11/topics/i18n/LANGUAGE_CODE = 'zh-hans'TIME_ZONE = 'Asia/Shanghai'USE_I18N = TrueUSE_L10N = TrueUSE_TZ = False# Static files (CSS,JavaScript,Images)# https://docs.djangoproject.com/en/1.11/howto/static-files/STATIC_URL = '/static/'STATICfileS_Dirs=(os.path.join(BASE_DIR,'static'),)AUTH_USER_MODEL = "drf_API.UserInfo"MEDIA_URL  = "/img/"MEDIA_ROOT = os.path.join(BASE_DIR,"img")# REST_FRAMEWORK = {#     'DEFAulT_AUTHENTICATION_CLASSES': (#         'rest_framework.authentication.TokenAuthentication',#     )# }
2.模型
from django.db import modelsfrom django.contrib.auth.models import AbstractUserfrom rest_framework import mixins# Create your models here.class UserInfo(AbstractUser):    avatar = models.fileFIEld(upload_to='avatar/',default='avatar/default.png')    class Meta:        verbose_name='用户表'        verbose_name_plural = verbose_nameclass  commodity(models.Model):    name = models.CharFIEld(max_length=60,db_column='商品名',null=True)    inventory = models.IntegerFIEld(db_column='库存',null=True)    cost = models.DecimalFIEld (max_digits=60,decimal_places=2,db_column='总成本',null=True)    selling_price= models.DecimalFIEld (max_digits=60,db_column='总销售价格',default=0)    batch = models.CharFIEld(max_length=60,db_column='批号',null=True)    quantity_in = models.IntegerFIEld(db_column='进货总数量',null=True)    sales_volume = models.IntegerFIEld(db_column='销售量总数量',default=0)    return_volume = models.IntegerFIEld(db_column='退货总数量',default=0)    is_delete = models.BooleanFIEld(default=False,db_column='是否删除')    def __str__(self):        return self.name    class Meta:        db_table = "库存表"class DaySales(models.Model):    date = models.CharFIEld(max_length=60,db_column='日期')    number = models.DecimalFIEld(max_digits=60,db_column='营业总额',null=True)    is_delete = models.BooleanFIEld(default=False,db_column='是否删除')    date_changed = models.DateTimeFIEld(auto_Now=True,db_column='最后修改日期')    def __str__(self):        return self.date    class Meta:        db_table = "日销售表"class DayStock(models.Model):    date = models.CharFIEld(max_length=60,db_column='进货总额',db_column='最后修改日期')    def __str__(self):        return self.date    class Meta:        db_table = "日进货表"class DayReturn(models.Model):    date = models.CharFIEld(max_length=60,db_column='日期')    number  = models.DecimalFIEld(max_digits=60,db_column='退货总额',db_column='最后修改日期')    def __str__(self):        return self.date    class Meta:        db_table = "日退货表"class commoditySales(models.Model):    name = models.CharFIEld(max_length=60,null=True)    data = models.ForeignKey('DaySales','ID',db_column='销售日期',db_column='销售价格',null=True)    sales_volume = models.IntegerFIEld(db_column='销售量数量',null=True)    batch = models.CharFIEld(max_length=60,db_column='最后修改日期')    def __str__(self):        return self.name    class Meta:        db_table = "商品销售表"class commodityStock(models.Model):    name = models.CharFIEld(max_length=60,null=True)    data = models.ForeignKey('DayStock',db_column='进货日期',db_column='单件成本',null=True)    Stock_volume = models.IntegerFIEld( db_column='进货数量',db_column='最后修改日期')    def __str__(self):        return self.name    class Meta:        db_table = "商品进货表"class commodityReturn(models.Model):    name = models.CharFIEld(max_length=60,null=True)    data = models.ForeignKey('DayReturn',db_column='退货日期',db_column='退货价格',null=True)    return_volume = models.IntegerFIEld( db_column='退货数量',db_column='最后修改日期')    def __str__(self):        return self.name    class Meta:        db_table = "商品退货表"
3.路由
"""drf_test URL ConfigurationThe `urlpatterns` List routes URLs to vIEws. For more information please see:    https://docs.djangoproject.com/en/1.11/topics/http/urls/Examples:Function vIEws    1. Add an import:  from my_app import vIEws    2. Add a URL to urlpatterns:  url(r'^$',vIEws.home,name='home')Class-based vIEws    1. Add an import:  from other_app.vIEws import Home    2. Add a URL to urlpatterns:  url(r'^$',Home.as_vIEw(),name='home')Including another URLconf    1. import the include() function: from django.conf.urls import url,include    2. Add a URL to urlpatterns:  url(r'^blog/',include('blog.urls'))"""from django.conf.urls import urlfrom django.contrib import adminfrom django_filters import vIEwsfrom drf_API.vIEws import userfrom drf_API.vIEws import commodityfrom django.vIEws.static import servefrom .settings import MEDIA_ROOTurlpatterns = [    url(r'^admin/',admin.site.urls),url(r'^register/',user.register),url(r'^test/',user.test),url(r'^login/',user.login),url(r'^loginout/',user.loginout),url(r'^get_code/',user.get_code),url(r'^show/',commodity.Show.as_vIEw()),url(r'^add/',commodity.Add.as_vIEw()),url(r'^del/',commodity.Del.as_vIEw()),url(r'^show_del/',commodity.ShowDel.as_vIEw()),url(r'^sales/',commodity.Sales.as_vIEw()),url(r'^return/',commodity.Return.as_vIEw()),url(r'',user.index),url(r'^img/(?P<path>.*)',serve,{'document_root': MEDIA_ROOT}),]
4.用户视图user.py
from django.shortcuts import render,httpResponse,redirectfrom django.http import JsonResponsefrom PIL import Image,ImageDraw,ImageFontimport randomfrom io import BytesIOfrom django.contrib import authfrom drf_API.userinfo_form import Registerfrom drf_API import modelsfrom rest_framework.throttling import SimpleRateThrottledef test(request):    return render(request,'aa.HTML')def register(request):    if request.method=='GET':        form=Register()        return render(request,'register.HTML',{'form':form})    elif request.is_AJAX():        response={'code':100,'msg':None}        form = Register(request.POST)        if form.is_valID():            #校验通过的数据            clean_data=form.cleaned_data            #把re_pwd剔除            clean_data.pop('re_pwd')            #取出头像            avatar=request.fileS.get('avatar')            if avatar:                clean_data['avatar']=avatar            user=models.UserInfo.objects.create_user(**clean_data)            if user:                response['msg'] = '创建成功'            else:                response['code'] = 103                response['msg'] = '创建失败'        else:            response['code']=101            #把校验不通过的数据返回            response['msg']=form.errors            print(type(form.errors))        return JsonResponse(response,safe=False)def login(request):    if request.method=='GET':        return render(request,'login.HTML')    else:        print(request.POST)        user_name=request.POST.get('name')        pwd=request.POST.get('pwd')        code=request.POST.get('code')        user=auth.authenticate(username=user_name,password=pwd)        print(user)        if request.session.get('code').upper() !=code.upper(): #忽略大小写            return httpResponse('验证码错误')        elif not user:            return httpResponse('账号密码错误')        else:            auth.login(request,user)            return redirect('/show/')def get_code(request):    if request.method == 'GET':        img = Image.new('RGB',(350,40),(random.randint(0,255),random.randint(0,255)))        # 写文字        # 生成一个字体对象        Font = ImageFont.truetype('/static/Gabriola.ttf',34)        # 调用方法,返回一个画板对象        draw = ImageDraw.Draw(img)        new_text =''        x = 100        # 生成随机4位数字        text_chiose = 'zxcvbnmasdfghjklqwertyup23456789ZXCVBNMASDFGHJKLQWERTYUP'        text_List=random.sample(text_chiose,4)        for text in text_List:            x+=20            y = random.randint(1,5)            draw.text((x,y),text,255)),Font=Font)            new_text +=text        # 加点线        wIDth = 320        height = 35        for i in range(2):            x1 = random.randint(0,wIDth)            x2 = random.randint(0,wIDth)            y1 = random.randint(0,height)            y2 = random.randint(0,height)            # 在图片上画线            draw.line((x1,y1,x2,y2),fill=(random.randint(0,255)))        for i in range(10):            # 画点            draw.point([random.randint(0,wIDth),height)],255)))            x = random.randint(0,wIDth)            y = random.randint(0,height)            # 画弧形            draw.arc((x,y,x + 4,y + 4),90,255)))        print(new_text)        #存在session中        request.session['code']=new_text        #存内存        f = BytesIO()        img.save(f,'png')        return httpResponse(f.getvalue())def loginout(request):    auth.logout(request)    return redirect('/login')def index(request):    return render(request,'index.HTML')
5.商品视图commodity.py

这里Return视图类有点偷懒了里面变量名用的非常非常不规范请见谅

import datetimefrom django.shortcuts import render,httpResponsefrom rest_framework.vIEws import APIVIEwfrom drf_API.models import *class Show(APIVIEw):    def get(self,request):        commodity_List = commodity.objects.filter(is_delete=False).order_by('name').all()        print(commodity_List)        return render(request,'show.HTML',{'commodity_List': commodity_List})class Add(APIVIEw):    def get(self,'add.HTML')    def post(self,request):        print(request.POST)        name = request.POST.get('name')  # type:str        batch = request.POST.get('batch')  # type:str        cost = request.POST.get('cost')  # type:str        Stock_volume = request.POST.get('Stock_volume')  # type:str        time = str(datetime.datetime.Now()).split(' ')[0].replace('-','')        DayStock_obj = DayStock.objects.filter(date=time).first()        try:            number = float(cost) * int(Stock_volume)        except:            return httpResponse('数量和价格请输入数字')        try:            if not DayStock_obj:                DayStock_obj = DayStock.objects.create(date=time,number=number)            else:                old_number = float(DayStock_obj.number)                DayStock_obj.number = old_number + number                DayStock_obj.save()            commodityStock_obj = commodityStock.objects.create(name=name,data=DayStock_obj,cost=number,Stock_volume=int(Stock_volume),batch=batch)            obj = commodity.objects.filter(is_delete=False,name=name,batch=batch).first()            if obj:                obj.quantity_in += int(Stock_volume)                obj.inventory += int(Stock_volume)                old_number = float(obj.cost)                obj.cost = old_number + number                obj.save()            else:                commodity.objects.create(name=name,inventory=int(Stock_volume),cost=float(cost),quantity_in=int(Stock_volume),batch=batch)            return httpResponse('添加成功')        except:            return httpResponse('添加失败')class Del(APIVIEw):    def get(self,'del.HTML',{'commodity_List': commodity_List})    def post(self,request):        c_ID = request.POST.get('c_ID')        commodity_obj = commodity.objects.filter(ID=c_ID).first()        commodity_obj.is_delete = True        commodity_obj.save()        return httpResponse('删除成功')class ShowDel(APIVIEw):    def get(self,request):        commodity_List = commodity.objects.filter(is_delete=True).all()        print(commodity_List)        return render(request,'show_del.HTML',request):        c_ID = request.POST.get('c_ID')        commodity_obj = commodity.objects.filter(ID=c_ID).first()        commodity_obj.is_delete = False        commodity_obj.save()        return httpResponse('恢复成功')class Sales(APIVIEw):    def get(self,'sales.HTML',request):        c_ID = request.POST.get('c_ID')        selling_price = request.POST.get('selling_price')        sales_volume = request.POST.get('sales_volume')        try:            selling_price = float(selling_price)            sales_volume = int(sales_volume)        except:            return httpResponse('数量和价格请输入数字')        try:            commodity_obj = commodity.objects.filter(ID=c_ID).first()            name = commodity_obj.name            batch = commodity_obj.batch            time = str(datetime.datetime.Now()).split(' ')[0].replace('-','')            DaySales_obj = DaySales.objects.filter(date=time).first()            number = selling_price * sales_volume            if not DaySales_obj:                DaySales_obj = DaySales.objects.create(date=time,number=number)            else:                old_number = float(commodity_obj.selling_price)                DaySales_obj.number = old_number + number                DaySales_obj.save()            commoditySales_obj = commoditySales.objects.create(name=name,data=DaySales_obj,selling_price=selling_price,sales_volume=sales_volume,batch=batch)            commodity_obj.sales_volume += sales_volume            commodity_obj.inventory -= sales_volume            old_number = float(commodity_obj.selling_price)            commodity_obj.selling_price = old_number + number            commodity_obj.save()            return httpResponse('出售成功')        except:            return httpResponse('数据异常')class Return(APIVIEw):    def get(self,'return.HTML','')            DayReturn_obj = DayReturn.objects.filter(date=time).first()            number = selling_price * sales_volume            if not DayReturn_obj:                DayReturn_obj = DayReturn.objects.create(date=time,number=number)            else:                old_number = float(commodity_obj.selling_price)                DayReturn_obj.number = old_number + number                DayReturn_obj.save()            commodityReturn_obj = commodityReturn.objects.create(name=name,data=DayReturn_obj,cost=selling_price,return_volume=sales_volume,batch=batch)            commodity_obj.return_volume += sales_volume            commodity_obj.inventory -= sales_volume            old_number = float(commodity_obj.selling_price)            commodity_obj.selling_price = old_number + number            commodity_obj.save()            return httpResponse('退货成功')        except:            return httpResponse('数据异常')
6.网页模板template.HTML
<!DOCTYPE HTML><HTML lang="zh"><head>    <Meta charset="UTF-8">    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/CSS/bootstrap.min.CSS">    <script src="/static/jquery-3.4.1.min.Js"></script>    <script src="/static/bootstrap-3.3.7-dist/Js/bootstrap.min.Js"></script>    <Title>{% block Title_text %}{% endblock %}</Title></head><style>    table{            background: antiquewhite;    }    .header {        position: fixed;        top: 0;        left: 0;        height: 100px;        wIDth: 100%;        background: red;    }    .header_left {        position: absolute;        line-height: 100px;        Font-size: 50px;        wIDth: 20%;        text-align: center;        background: black;        color: white;    }        .header_mIDdle {        position: absolute;        line-height: 100px;        Font-size: 50px;        wIDth: 20%;        background: none;        color: white;        left: 20%;    }    .header_right {        float: right;    }    .body {        position: fixed;        top: 100px;        left: 0;        bottom: 20px;        wIDth: 100%;    }    .body_left {        position: fixed;        top: 100px;        bottom: 20px;        wIDth: 20%;        background: white;        left: 0;    }    .body_right {        overflow: auto;        position: fixed;        top: 100px;        left: 20%;        bottom: 20px;        wIDth: 80%;        background: #2aabd2;    }    .footer {        position: fixed;        left: 0;        bottom: 0;        height: 20px;        wIDth: 100%;        background: black;    }</style>{% block new_CSS %}{% endblock %}<body><div >    <div >管理系统</div>    <div ><span ID="clock"></span></div>    <div >        {% if request.user.is_authenticated %}            <span><img src=http://127.0.0.1:8000/img/{{ request.user.avatar }} alt="" >尊敬的{{ request.user.username }}</span>            <span >  <button  type="button" ID="dropdownMenu1" data-toggle="dropdown"          aria-haspopup="true" aria-expanded="true" >    更多 *** 作    <span ></span>  </button>  <ul  aria-labelledby="dropdownMenu1" >    <li><a href="#" >修改头像</a><a href="#">修改密码</a></li>    <li role="separator" ></li>    <li><a href="/loginout/" >登出</a></li>  </ul></span>        {% else %}            <spen ><a                    href="/login/">登入</a>{{ request.user.username }}</spen>            <spen ><a                    href="/register/">注册</a>{{ request.user.username }}</spen>        {% endif %}    </div></div><div >    <div >        <ul >            <li role="presentation" ><a>库存管理</a></li>            <li role="presentation"><a href="/show/">商品库存</a></li>            <li role="presentation"><a href="/add/">商品进货</a></li>            <li role="presentation"><a href="/return/">商品退货</a></li>            <li role="presentation"><a href="/sales/">商品销售</a></li>            <li role="presentation"><a href="/del/">删除库存商品</a></li>            <li role="presentation"><a href="/show_del/">删除商品查看</a></li>        </ul>    </div>    <div >        {% block data %}        {% endblock %}    </div></div><div ></div></body></HTML><script>    function get_time() {        var obj = new Date();        var hour = obj.getHours();        var min = obj.getMinutes();        var seconds = obj.getSeconds();        if (parseInt(seconds)<10)seconds='0'+seconds;        if (parseInt(hour)<10)hour='0'+hour;        if (parseInt(min)<10)min='0'+min;        var time = hour + ':' + min + ':' + seconds        var clock = document.querySelector('#clock')        clock.innerText = time    }    setInterval(get_time,1000)</script>{% block new_Js %}{% endblock %}
注册register.HTML
{% extends 'template.HTML' %}{% block Title_text %}    注册{% endblock %}{% block new_CSS %}{% endblock %}{% block data %}    <div >        <div >            <div >                <h1>注册</h1>                <form ID="my_form">                    {% for foo in form %}                        <div >                            {#foo.auto_ID   就是foo生成的input的ID#}                            <label for="{{ foo.auto_ID }}">{{ foo.label }}</label>                            {{ foo }} <span  ></span>                        </div>                    {% endfor %}                    <div >                        <label for="ID_file">头像                            <img src="/img/avatar/default.png" wIDth="80" height="80"                                  ID="ID_img">                        </label>                        <input type="file" name="file" ID="ID_file" >                    </div>                    <input type="button"  value="提交" ID="ID_submit">                </form>            </div>        </div>    </div>{% endblock %}{% block new_Js %}    <script>        //当该控件发生变化,响应该事件        $("#ID_file").change(function () {            //alert(1)            //取到文件对象            var file = $("#ID_file")[0].files[0]            //放到img控件上,借助于filereader 中间的东西,文件阅读器            //生成一个文件阅读器对象赋值给filereader            var filereader = new fileReader()            //把文件读到filereader对象中            //读文件需要时间,需要文件读完再去 *** 作img            filereader.readAsDataURL(file)            filereader.onload = function () {                $("#ID_img").attr('src',filereader.result)            }        })        $("#ID_submit").click(function () {            //AJAX 上传文件            var formdata = new FormData()            //一个一个往里添加,稍微复杂,用简便方法            // formdata.append('name',$("#ID_name").val())            // formdata.append('pwd',$("#ID_pwd").val())            //简便方法            //form 对象的serializeArray,它会把form中的数据包装到一个对象中(不包含文件)            var my_form_data = $("#my_form").serializeArray()            //console.log(typeof my_form_data)            //console.log(my_form_data)            //jq的循环,传两个参数,第一个是要循环的对象,第二个参数是一个匿名函数            $.each(my_form_data,function (k,v) {                {#console.log(k)#}                {#console.log(v)#}                formdata.append(v.name,v.value)            })            formdata.append('avatar',$("#ID_file")[0].files[0])            $.AJAX({                url: '/register/',type: 'post',processData: false,//告诉jquery不要去处理发送的数据                ContentType: false,// 告诉jquery不要去设置Content-Type请求头                data: formdata,success: function (data) {                    //console.log(data)                    if (data.code == 100) {                        location.href = '/login/'                    } else if (data.code == 101) {                        $.each(data.msg,v) {                            console.log(k)                            console.log(v)                            $("#ID_" + k).next().HTML(v[0])                            if (k == '__all__') {                                $("#ID_re_pwd").next().HTML(v[0])                            }                        })                    }                    //定时器                    setTimeout(function () {                        $(".error").HTML("")                    },3000)                }            })        })    </script>{% endblock %}
登入login.HTML
{% extends 'template.HTML' %}{% block Title_text %}    登入{% endblock %}{% block new_CSS %}    <style>        .img-code:hover{        }    </style>{% endblock %}{% block data %}    <div >        <div >            <div >                {% csrf_token %}                <h1>登陆</h1>                <form action="">                    <div >                        <label for="ID_name">用户名</label>                        <input type="text" name="name" ID="ID_name" >                    </div>                    <div >                        <label for="pwd">密码</label>                        <input type="password" name="pwd" ID="pwd" >                    </div>                    <div >                        <label for="ID_code">验证码</label>                        <div >                            <div >                                <input type="text" name="code" ID="ID_code" >                            </div>                            <div  ID="img">                                <img src="/get_code/" height="40" wIDth="240" >                            </div>                        </div>                    </div>                    <input type="button" value="提交"  ID="up_data">                    <span  ID="msg"></span>                </form>            </div>        </div>    </div>{% endblock %}{% block new_Js %}    <script>        $('.img-code').click(function () {            var img_code_src = $(this).attr('src');            img_code_src += '1';            console.log(img_code_src);            $(this).attr('src',img_code_src)        })    </script>    <script>        $('#up_data').click(function () {            $.AJAX({                type: 'post',url: '/login/',data: {                    'name': $('#ID_name').val(),'pwd': $('#pwd').val(),'code': $('#ID_code').val(),'csrfmIDdlewaretoken': '{{csrf_token}}'                },success: function (msg) {                    console.log(msg);                    $('#msg').text(msg);                    if (msg == '登入成功') {                        console.log('sb');                    }                }            })        })    </script>{% endblock %}
首页index.HTML
{% extends 'template.HTML' %}{% block Title_text %}    首页{% endblock %}{% block new_CSS %}{% endblock %}{% block data %}    <div  >欢迎光临    </div>{% endblock %}{% block new_Js %}{% endblock %}
进货add.HTML
{% extends 'template.HTML' %}{% block Title_text %}    添加商品{% endblock %}{% block new_CSS %}{% endblock %}{% block data %}    <form action="" method="post">        {% csrf_token %}        <label for="name">商品名</label>        <input type="text" ID="name" name="name">        <label for="Stock_volume">商品数量</label>        <input type="text" ID="Stock_volume" name="Stock_volume">        <label for="batch">商品批号</label>        <input type="text" ID="batch" name="batch">        <label for="cost">商品单价(元)</label>        <input type="text" ID="cost" name="cost">        <input type="button" value="提交" >    </form>    <div ></div>{% endblock %}{% block new_Js %}    <script>    var new_show_msg =''        var custom_button = document.querySelector('.custom_button');        custom_button.onclick = function () {            var name = document.querySelector('#name').value;            var Stock_volume = document.querySelector('#Stock_volume').value;            var batch = document.querySelector('#batch').value;            var cost = document.querySelector('#cost').value;            var show_msg = '商品名:' + name + '\n批号:' + batch + '\n数量:' + Stock_volume + '\n成本单价:' + cost+'元'            if (name && Stock_volume && batch && cost) {                if (confirm(show_msg)){                    $.AJAX(                        {                            type: 'post',url: '/add/',data: {                                'name': name,'Stock_volume': Stock_volume,'batch': batch,'cost': cost,'csrfmIDdlewaretoken': '{{csrf_token}}'                            },success: function (msg) {                                var show = document.querySelector('.msg')                                new_show_msg += '<div ><div >'+msg+'</div>'+show_msg+'</div>'                                show.INNERHTML=new_show_msg                            }                        }                    )                }            } else {                alert('内容不能为空')            }        }    </script>{% endblock %}
销售sales.HTML
{% extends 'template.HTML' %}{% block Title_text %}    删除商品库存{% endblock %}{% block new_CSS %}{% endblock %}{% block data %}    <table >        <thead>        <tr>            <th></th>            <th>商品名</th>            <th>商品批号</th>            <th>库存</th>            <th>总成本</th>            <th>总销售额</th>            <th>进货总数量</th>            <th>销售量总数量</th>            <th>退货总数量</th>            <th>销售</th>        </tr>        </thead>        <tbody>        {% for commodity_obj in commodity_List %}            <tr>                <th scope="row">1</th>                <td>{{ commodity_obj.name }}</td>                <td>{{ commodity_obj.batch }}</td>                <td>{{ commodity_obj.inventory }}</td>                <td>{{ commodity_obj.cost }}</td>                <td>{{ commodity_obj.selling_price }}</td>                <td>{{ commodity_obj.quantity_in }}</td>                <td>{{ commodity_obj.sales_volume }}</td>                <td>{{ commodity_obj.return_volume }}</td>                <td>                    <button  inventory={{ commodity_obj.inventory }} batch={{ commodity_obj.batch }} c_ID={{ commodity_obj.ID }}>出售</button>                </td>            </tr>        {% endfor %}        </tbody>    </table>{% endblock %}{% block new_Js %}    <script>        var del_button = document.querySelectorAll('.del_button')        for (var index = 0; index < del_button.length; index++) {            del_button[index].onclick = function () {                if (confirm('是否确定出售')) {                    var selling_price = parsefloat(prompt('出售价格'));                    var sales_volume = parseInt(prompt('出售数量'));                    var c_ID = this.getAttribute('c_ID');                    var inventory = this.getAttribute('inventory');                    if(sales_volume<=inventory){                                 $.AJAX({                        url: /sales/,data: {                            'c_ID': c_ID,'selling_price': selling_price,'sales_volume': sales_volume,'csrfmIDdlewaretoken': '{{csrf_token}}'                        },success: function (msg) {                            alert(msg)                            window.location.replace('/sales/')                    }                    })                    }else {                        alert('库存不足')                    }                }            }        }    </script>{% endblock %}
退货return.HTML
{% extends 'template.HTML' %}{% block Title_text %}    删除商品库存{% endblock %}{% block new_CSS %}{% endblock %}{% block data %}    <table >        <thead>        <tr>            <th></th>            <th>商品名</th>            <th>商品批号</th>            <th>库存</th>            <th>总成本</th>            <th>总销售额</th>            <th>进货总数量</th>            <th>销售量总数量</th>            <th>退货总数量</th>            <th>退货</th>        </tr>        </thead>        <tbody>        {% for commodity_obj in commodity_List %}            <tr>                <th scope="row">1</th>                <td>{{ commodity_obj.name }}</td>                <td>{{ commodity_obj.batch }}</td>                <td>{{ commodity_obj.inventory }}</td>                <td>{{ commodity_obj.cost }}</td>                <td>{{ commodity_obj.selling_price }}</td>                <td>{{ commodity_obj.quantity_in }}</td>                <td>{{ commodity_obj.sales_volume }}</td>                <td>{{ commodity_obj.return_volume }}</td>                <td>                    <button  inventory={{ commodity_obj.inventory }} batch={{ commodity_obj.batch }} c_ID={{ commodity_obj.ID }}>退货</button>                </td>            </tr>        {% endfor %}        </tbody>    </table>{% endblock %}{% block new_Js %}    <script>        var del_button = document.querySelectorAll('.del_button')        for (var index = 0; index < del_button.length; index++) {            del_button[index].onclick = function () {                if (confirm('是否确定退货')) {                    var selling_price = parsefloat(prompt('退货单价'));                    var sales_volume = parseInt(prompt('退货数量'));                    var c_ID = this.getAttribute('c_ID');                    var inventory = this.getAttribute('inventory');                    if(sales_volume<=inventory){                                 $.AJAX({                        url: /return/,success: function (msg) {                            alert(msg)                            window.location.replace('/return/')                    }                    })                    }else {                        alert('库存不足')                    }                }            }        }    </script>{% endblock %}
删除商品del.HTML
{% extends 'template.HTML' %}{% block Title_text %}    删除商品库存{% endblock %}{% block new_CSS %}{% endblock %}{% block data %}    <table >        <thead>        <tr>            <th></th>            <th>商品名</th>            <th>商品批号</th>            <th>库存库存</th>            <th>总成本</th>            <th>总销售额</th>            <th>进货总数量</th>            <th>销售量总数量</th>            <th>退货总数量</th>            <th>是否删除</th>        </tr>        </thead>        <tbody>        {% for commodity_obj in commodity_List %}            <tr>                <th scope="row">1</th>                <td>{{ commodity_obj.name }}</td>                <td>{{ commodity_obj.batch }}</td>                <td>{{ commodity_obj.inventory }}</td>                <td>{{ commodity_obj.cost }}</td>                <td>{{ commodity_obj.selling_price }}</td>                <td>{{ commodity_obj.quantity_in }}</td>                <td>{{ commodity_obj.sales_volume }}</td>                <td>{{ commodity_obj.return_volume }}</td>                <td>                    <button  c_ID={{ commodity_obj.ID }}>删除</button>                </td>            </tr>        {% endfor %}        </tbody>    </table>{% endblock %}{% block new_Js %}    <script>        var del_button = document.querySelectorAll('.del_button')        for (var index = 0; index < del_button.length; index++) {            del_button[index].onclick = function () {                if (confirm('是否确定删除')) {                    var c_ID = this.getAttribute('c_ID');                    $.AJAX({                        url: /del/,success: function (msg) {                            alert(msg)                            window.location.replace('/del/')                    }                    })                }            }        }    </script>{% endblock %}
展示show.HTML
{% extends 'template.HTML' %}{% block Title_text %}    查看商品{% endblock %}{% block new_CSS %}{% endblock %}{% block data %}<table >      <thead>        <tr>          <th></th>          <th>商品名</th>          <th>批号</th>          <th>库存库存</th>          <th>总成本</th>          <th>总销售额</th>          <th>进货总数量</th>          <th>销售量总数量</th>          <th>退货总数量</th>        </tr>      </thead>      <tbody>        {% for commodity_obj in commodity_List %}            <tr>          <th scope="row">1</th>          <td>{{ commodity_obj.name}}</td>          <td>{{ commodity_obj.batch}}</td>          <td>{{ commodity_obj.inventory}}</td>          <td>{{ commodity_obj.cost}}</td>          <td>{{ commodity_obj.selling_price}}</td>          <td>{{ commodity_obj.quantity_in}}</td>          <td>{{ commodity_obj.sales_volume}}</td>          <td>{{ commodity_obj.return_volume}}</td>        </tr>        {% endfor %}      </tbody>    </table>{% endblock %}{% block new_Js %}{% endblock %}
展示删除show_del.HTML
{% extends 'template.HTML' %}{% block Title_text %}    删除商品查看及还原{% endblock %}{% block new_CSS %}{% endblock %}{% block data %}    <table >        <thead>        <tr>            <th></th>            <th>商品名</th>            <th>商品批号</th>            <th>库存库存</th>            <th>总成本</th>            <th>总销售额</th>            <th>进货总数量</th>            <th>销售量总数量</th>            <th>退货总数量</th>            <th>是否还原</th>        </tr>        </thead>        <tbody>        {% for commodity_obj in commodity_List %}            <tr>                <th scope="row">1</th>                <td>{{ commodity_obj.name }}</td>                <td>{{ commodity_obj.batch }}</td>                <td>{{ commodity_obj.inventory }}</td>                <td>{{ commodity_obj.cost }}</td>                <td>{{ commodity_obj.selling_price }}</td>                <td>{{ commodity_obj.quantity_in }}</td>                <td>{{ commodity_obj.sales_volume }}</td>                <td>{{ commodity_obj.return_volume }}</td>                <td>                    <button  c_ID={{ commodity_obj.ID }}>还原</button>                </td>            </tr>        {% endfor %}        </tbody>    </table>{% endblock %}{% block new_Js %}    <script>        var del_button = document.querySelectorAll('.del_button')        for (var index = 0; index < del_button.length; index++) {            del_button[index].onclick = function () {                if (confirm('是否确定还原')) {                    var c_ID = this.getAttribute('c_ID');                    $.AJAX({                        url: /show_del/,success: function (msg) {                            alert(msg)                            window.location.replace('/show_del/')                    }                    })                }            }        }    </script>{% endblock %}
五.自动生成项目目录树状图
import osdef dirsTree():    PATH = os.path.dirname(__file__)    print(PATH)    lis = os.Listdir(PATH)    if lis != None:        for a in lis:            print(f'|___{a}')            if '.' not in a:                a_path = os.path.join(PATH,a)                lis_2 = os.Listdir(a_path)                if lis_2 != None:                    for b in lis_2:                        if b != '__pycache__':                            print(f'|    |___{b}')if __name__ == '__main__':                      dirsTree() #弄了两级也没有用递归来做啦
总结

以上是内存溢出为你收集整理的国庆手撸商品管理系统(三)全部内容,希望文章能够帮你解决国庆手撸商品管理系统(三)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1223029.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存