💕💕作者:计算机源码社
💕💕个人简介:本人七年开发经验,擅长Java、微信小程序、Python、Android等,大家有这一块的问题可以一起交流!
💕💕学习资料、程序开发、技术解答、代码讲解、文档报告
💕💕JavaWeb项目
💕💕微信小程序项目
💕💕Python项目
💕💕Android项目
文章目录
- 1、绪论
- 1.1 项目背景
- 2、核心功能模块
- 3、项目功能演示
- 4、项目页面展示
- 4、 菜品订单核心代码
1、绪论
1.1 项目背景
基随着计算机技术和信息化发展,网络遍布生活每一个角落,给人们生活带来了便捷,许多餐饮行业引用了计算机和网络技术,好的技术推动行业发展。因此一个在线选择菜品、点单、结算、管理菜品和用户信息的餐厅在线点餐系统,符合当今网络社会现代化管理模式,同时降低了经营店家的管理成本,提高了信息传达的效率和准确性。
2、核心功能模块
Python基于Django餐厅点餐选座系统的设计根据实际调研现在社会真实存在的一些餐厅现有的实际订餐流程,了解餐厅老板和就餐的用户的需求,最后以这些需求角度进行设计。其中包括店家角度的餐桌管理、订单管理、菜品管理、用户管理、订单的管理;用户角度的菜品介绍、预订餐桌、收藏菜品、订单结算等。系统实现主要使用了Python语言,利用Django框架,以及使用MySQL数据库、PyCharm 2021.3开发工具。
3、项目功能演示
Python基于Django餐厅点餐选座系统
4、项目页面展示
4、 菜品订单核心代码
'''后台新增'''if request.method in ["POST", "GET"]:msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}req_dict = request.session.get("req_dict")if 'clicktime' in req_dict.keys():del req_dict['clicktime']tablename=request.session.get("tablename")__isAdmin__ = NoneallModels = apps.get_app_config('main').get_models()for m in allModels:if m.__tablename__==tablename:try:__isAdmin__ = m.__isAdmin__except:__isAdmin__ = Nonebreak#获取全部列名columns= caipindingdan.getallcolumn( caipindingdan, caipindingdan)if tablename!='users' and req_dict.get("userid")!=None and 'userid' in columns and __isAdmin__!='是':params=request.session.get("params")req_dict['userid']=params.get('id')error= caipindingdan.createbyreq(caipindingdan,caipindingdan, req_dict)if error!=None:msg['code'] = crud_error_codemsg['msg'] = errorreturn JsonResponse(msg)def caipindingdan_add(request):'''前台新增'''if request.method in ["POST", "GET"]:msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}req_dict = request.session.get("req_dict")#获取全部列名columns= caipindingdan.getallcolumn( caipindingdan, caipindingdan)try:__authSeparate__=caipindingdan.__authSeparate__except:__authSeparate__=Noneif __authSeparate__=="是":tablename=request.session.get("tablename")if tablename!="users" and 'userid' in columns:try:req_dict['userid']=request.session.get("params").get("id")except:passtry:__foreEndListAuth__=caipindingdan.__foreEndListAuth__except:__foreEndListAuth__=Noneif __foreEndListAuth__ and __foreEndListAuth__!="否":tablename=request.session.get("tablename")if tablename!="users":req_dict['userid']=request.session.get("params").get("id")error= caipindingdan.createbyreq(caipindingdan,caipindingdan, req_dict)if error!=None:msg['code'] = crud_error_codemsg['msg'] = errorreturn JsonResponse(msg)def caipindingdan_thumbsup(request,id_):'''点赞:表属性thumbsUp[是/否],刷表新增thumbsupnum赞和crazilynum踩字段,'''if request.method in ["POST", "GET"]:msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}req_dict = request.session.get("req_dict")id_=int(id_)type_=int(req_dict.get("type",0))rets=caipindingdan.getbyid(caipindingdan,caipindingdan,id_)update_dict={"id":id_,}if type_==1:#赞update_dict["thumbsupnum"]=int(rets[0].get('thumbsupnum'))+1elif type_==2:#踩update_dict["crazilynum"]=int(rets[0].get('crazilynum'))+1error = caipindingdan.updatebyparams(caipindingdan,caipindingdan, update_dict)if error!=None:msg['code'] = crud_error_codemsg['msg'] = errorreturn JsonResponse(msg)def caipindingdan_info(request,id_):''''''if request.method in ["POST", "GET"]:msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}data = caipindingdan.getbyid(caipindingdan,caipindingdan, int(id_))if len(data)>0:msg['data']=data[0]#浏览点击次数try:__browseClick__= caipindingdan.__browseClick__except:__browseClick__=Noneif __browseClick__=="是" and "clicknum" in caipindingdan.getallcolumn(caipindingdan,caipindingdan):try:clicknum=int(data[0].get("clicknum",0))+1except:clicknum=0+1click_dict={"id":int(id_),"clicknum":clicknum}ret=caipindingdan.updatebyparams(caipindingdan,caipindingdan,click_dict)if ret!=None:msg['code'] = crud_error_codemsg['msg'] = retreturn JsonResponse(msg)def caipindingdan_detail(request,id_):''''''if request.method in ["POST", "GET"]:msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}data =caipindingdan.getbyid(caipindingdan,caipindingdan, int(id_))if len(data)>0:msg['data']=data[0]#浏览点击次数try:__browseClick__= caipindingdan.__browseClick__except:__browseClick__=Noneif __browseClick__=="是" and "clicknum" in caipindingdan.getallcolumn(caipindingdan,caipindingdan):try:clicknum=int(data[0].get("clicknum",0))+1except:clicknum=0+1click_dict={"id":int(id_),"clicknum":clicknum}ret=caipindingdan.updatebyparams(caipindingdan,caipindingdan,click_dict)if ret!=None:msg['code'] = crud_error_codemsg['msg'] = retforeturn JsonResponse(msg)def caipindingdan_update(request):''''''if request.method in ["POST", "GET"]:msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}req_dict = request.session.get("req_dict")if req_dict.get("mima") and req_dict.get("password"):if "mima" not in caipindingdan.getallcolumn(caipindingdan,caipindingdan) :del req_dict["mima"]if "password" not in caipindingdan.getallcolumn(caipindingdan,caipindingdan) :del req_dict["password"]try:del req_dict["clicknum"]except:passerror = caipindingdan.updatebyparams(caipindingdan, caipindingdan, req_dict)if error!=None:msg['code'] = crud_error_codemsg['msg'] = errorreturn JsonResponse(msg)def caipindingdan_delete(request):'''批量删除'''if request.method in ["POST", "GET"]:msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}req_dict = request.session.get("req_dict")error=caipindingdan.deletes(caipindingdan,caipindingdan,req_dict.get("ids"))if error!=None:msg['code'] = crud_error_codemsg['msg'] = errorreturn JsonResponse(msg)def caipindingdan_vote(request,id_):'''浏览点击次数(表属性[browseClick:是/否],点击字段(clicknum),调用info/detail接口的时候后端自动+1)、投票功能(表属性[vote:是/否],投票字段(votenum),调用vote接口后端votenum+1)
统计商品或新闻的点击次数;提供新闻的投票功能'''if request.method in ["POST", "GET"]:msg = {"code": normal_code, "msg": mes.normal_code}data= caipindingdan.getbyid(caipindingdan, caipindingdan, int(id_))for i in data:votenum=i.get('votenum')if votenum!=None:params={"id":int(id_),"votenum":votenum+1}error=caipindingdan.updatebyparams(caipindingdan,caipindingdan,params)if error!=None:msg['code'] = crud_error_codemsg['msg'] = errorreturn JsonResponse(msg)def caipindingdan_importExcel(request):if request.method in ["POST", "GET"]:msg = {"code": normal_code, "msg": "成功", "data": {}}excel_file = request.FILES.get("file", "")file_type = excel_file.name.split('.')[1]if file_type in ['xlsx', 'xls']:data = xlrd.open_workbook(filename=None, file_contents=excel_file.read())table = data.sheets()[0]rows = table.nrowstry:for row in range(1, rows):row_values = table.row_values(row)req_dict = {}caipindingdan.createbyreq(caipindingdan, caipindingdan, req_dict)except:passelse:msg.code = 500msg.msg = "文件类型错误"return JsonResponse(msg)def caipindingdan_sendemail(request):if request.method in ["POST", "GET"]:req_dict = request.session.get("req_dict")code = random.sample(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 4)to = []to.append(req_dict['email'])send_mail('用户注册', '您的注册验证码是【'+''.join(code)+'】,请不要把验证码泄漏给其他人,如非本人请勿操作。', 'yclw9@qq.com', to, fail_silently = False)cursor = connection.cursor()cursor.execute("insert into emailregistercode(email,role,code) values('"+req_dict['email']+"','用户','"+''.join(code)+"')")msg = {"msg": "发送成功","code": 0}return JsonResponse(msg)def caipindingdan_autoSort2(request):if request.method in ["POST", "GET"]:req_dict = request.session.get("req_dict")cursor = connection.cursor()leixing = set()try:cursor.execute("select inteltype from storeup where userid = %d"%(request.session.get("params").get("id"))+" and tablename = 'caipindingdan' order by addtime desc")rows = cursor.fetchall()for row in rows:for item in row:if item != None:leixing.add(item)except:leixing = set()L = []cursor.execute("select * from caipindingdan where $intelRecomColumn in ('%s"%("','").join(leixing)+"') union all select * from caipindingdan where $intelRecomColumn not in('%s"%("','").join(leixing)+"')")desc = cursor.descriptiondata_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()] for online_dict in data_dict:for key in online_dict:if 'datetime.datetime' in str(type(online_dict[key])):online_dict[key] = online_dict[key].strftime("%Y-%m-%d %H:%M:%S")else:passL.append(online_dict)return JsonResponse({"code": 0, "msg": '', "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":5,"list": L[0:6]}})def caipindingdan_value(request, xColumnName, yColumnName, timeStatType):if request.method in ["POST", "GET"]:msg = {"code": normal_code, "msg": "成功", "data": {}}where = ' where 1 = 1 'sql = ''if timeStatType == '日':sql = "SELECT DATE_FORMAT({0}, '%Y-%m-%d') {0}, sum({1}) total FROM caipindingdan {2} GROUP BY DATE_FORMAT({0}, '%Y-%m-%d')".format(xColumnName, yColumnName, where, '%Y-%m-%d')if timeStatType == '月':sql = "SELECT DATE_FORMAT({0}, '%Y-%m') {0}, sum({1}) total FROM caipindingdan {2} GROUP BY DATE_FORMAT({0}, '%Y-%m')".format(xColumnName, yColumnName, where, '%Y-%m')if timeStatType == '年':sql = "SELECT DATE_FORMAT({0}, '%Y') {0}, sum({1}) total FROM caipindingdan {2} GROUP BY DATE_FORMAT({0}, '%Y')".format(xColumnName, yColumnName, where, '%Y')L = []cursor = connection.cursor()cursor.execute(sql)desc = cursor.descriptiondata_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()] for online_dict in data_dict:for key in online_dict:if 'datetime.datetime' in str(type(online_dict[key])):online_dict[key] = online_dict[key].strftime("%Y-%m-%d %H:%M:%S")else:passL.append(online_dict)msg['data'] = Lreturn JsonResponse(msg)def caipindingdan_o_value(request, xColumnName, yColumnName):if request.method in ["POST", "GET"]:msg = {"code": normal_code, "msg": "成功", "data": {}}where = ' where 1 = 1 'sql = "SELECT {0}, sum({1}) AS total FROM caipindingdan {2} GROUP BY {0}".format(xColumnName, yColumnName, where)L = []cursor = connection.cursor()cursor.execute(sql)desc = cursor.descriptiondata_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()] for online_dict in data_dict:for key in online_dict:if 'datetime.datetime' in str(type(online_dict[key])):online_dict[key] = online_dict[key].strftime("%Y-%m-%d %H:%M:%S")else:passL.append(online_dict)msg['data'] = Lreturn JsonResponse(msg)def caipindingdan_alipay(request):if request.method in ["POST", "GET"]:alipay = AliPay(appid=settings.ALIPAY_APP_ID,app_notify_url=None,app_private_key_string=settings.APP_PRIVATE_KEY_STRING,alipay_public_key_string=settings.ALIPAY_PUBLIC_KEY_STRING,sign_type=settings.ALIPAY_SIGN_TYPE,debug=True,config=AliPayConfig(timeout=15))req_dict = request.session.get("req_dict")order_string = alipay.api_alipay_trade_page_pay(out_trade_no=req_dict['tradeno'],total_amount=req_dict['totalamount'],subject=req_dict['subject'],return_url='http://localhost:8080/django1mi5m/caipindingdan/notify',#notify_url='')pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_stringpay_url = '<form name="punchout_form" method="post" action="{0}"><input type="hidden" name="biz_content" ><input type="submit" value="立即支付" style="display: none"></form>'.format(pay_url)return JsonResponse({'code': 0, "data": pay_url})def caipindingdan_notify(request):if request.method in ["POST", "GET"]:req_dict = request.session.get("req_dict")out_trade_no = req_dict['out_trade_no']cursor = connection.cursor()return redirect('http://localhost:8080/django1mi5m/admin/dist/index.html#/caipindingdan')def caipindingdan_groupby(request):'''管理员用户:当表属性isAdmin=”是”,刷出来的用户表也是管理员,即page和list可以查看所有人的考试记录(同时应用于其他表)'''if request.method in ["POST", "GET"]:msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}req_dict = request.session.get("req_dict")#处理参数try:page1 = int(req_dict.get("page"))except:page1 = 1try:limit1 = int(req_dict.get("limit"))except:limit1 = 10#值为"是"仅能查看自己的记录和add接口后台赋值userid的值try:__authSeparate__ = caipindingdan.__authSeparate__except:__authSeparate__ = None# print(caipindingdan.getallcolumn(caipindingdan,caipindingdan))if __authSeparate__=="是":#print("req_dict==============>",req_dict)#如果当前表有userid字段,且通过身份认证if "userid" in caipindingdan.getallcolumn(caipindingdan,caipindingdan) and request.session.get("params")!=None:#参数增加useridreq_dict["userid"]=request.session.get("params").get("id")#如果当前表没有userid字段,且参数里有userid键值对if "userid" not in caipindingdan.getallcolumn(caipindingdan,caipindingdan) and "userid" in list(req_dict.keys()):#删除参数useriddel req_dict["userid"]try:del req_dict["page"]del req_dict["limit"]except:passtablename=request.session.get("tablename")if tablename=="users" and req_dict.get("userid")!=None:del req_dict["userid"]else:#判断当前登陆表是否具有管理员权限__isAdmin__ = NoneallModels = apps.get_app_config('main').get_models()for m in allModels:if m.__tablename__==tablename:try:__isAdmin__ = m.__isAdmin__except:__isAdmin__ = Nonebreak#是,则删除userid参数if __isAdmin__=="是":del req_dict["userid"]else:#否,则赋值userid参数req_dict["userid"]=request.session.get("params").get("id")print("req_dict===========>",req_dict)#本次分页查询start=limit1 * (page1 - 1)end=limit1 * (page1 - 1)+limit1+1datas = caipindingdan.objects.filter(**req_dict).\annotate(userids=Count('userid'),usernames=Count('username'),paperids=Count('paperid'),papernames=Count('papername')). \values("userid", "username", "paperid", "papername","myscore"). \all()[start:end]print("datas=============>", datas)print("datas=============>", datas.aggregate(myscore=Sum('myscore')))#处理分页查询所得数据try:data = [model_to_dict(i) for i in datas]except:data = datasdataDict = {}for i in data:keyName1="{}#{}#{}#{}".format(i.get("userid"),i.get("username"),i.get("paperid"),i.get("papername"))if dataDict.get(keyName1)==None:dataDict[keyName1]={"userid":i.get("userid"),"username":i.get("username"),"paperid":i.get("paperid"),"papername":i.get("papername"),"myscore":i.get("myscore")}else:dataDict[keyName1]["myscore"]=dataDict.get(keyName1).get("myscore")+i.get("myscore")#赋值分页查询所得数据dataList =list(dataDict.values())# 处理所有查询,计算总页数total = len(dataList)try:div = divmod(total, limit1)if div[1] > 0:totalPage = div[0] + 1else:totalPage = div[0]except:totalPage = 1# 赋值分页参数msg["data"] = {"pageSize": limit1,"total": total,"totalPage": totalPage,"currPage": page1,"list":dataList}return JsonResponse(msg)def caipindingdan_deleterecords(request):'''按键值对参数添加删除记录'''if request.method in ["POST", "GET"]:msg = {"code": normal_code, "msg": mes.normal_code}req_dict = request.session.get("req_dict")error=caipindingdan.deletebyparams(caipindingdan,caipindingdan,req_dict)if error!=None:msg['code'] = crud_error_codemsg['msg'] = errorreturn JsonResponse(msg)
def caipindingdan_flist(request):'''查看所有开放的帖列表(无需登录)'''if request.method in ["POST", "GET"]:msg = {"code": normal_code, "msg": mes.normal_code, "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":10,"list":[]}}req_dict = request.session.get("req_dict")msg['data']['list'], msg['data']['currPage'], msg['data']['totalPage'], msg['data']['total'], \msg['data']['pageSize'] = caipindingdan.page(caipindingdan, caipindingdan, req_dict)return JsonResponse(msg)def caipindingdan_list_id(request,id_):'''查看主贴和所有回帖内容(无需登录)'''if request.method in ["POST", "GET"]:msg = {"code": normal_code, "msg": mes.normal_code, "data": {"currPage":1,"totalPage":1,"total":1,"pageSize":10,"childs":[]},"id":int(id_)}params = {"id":int(id_)}datas = caipindingdan.retrieve(caipindingdan, caipindingdan)parent_id=0#当前id,也就是parent_id,找到了下一级,把下一级id赋值给current_id,当做下下一级id的paretn_idcurrent_id=0start_index=0#获取parentidfor index,i in enumerate(datas):if i.get('id')==params.get('id'):current_id=parent_id=i.get('id')start_index=indexmsg['data'].update(i)break#把疑似回帖的id放进ids数组id_data_dict={}#id和详情的键值对for i in datas:id_data_dict[i.get('id')]=idict1={}#部分层级,只获取上下级关系for v in id_data_dict.values():parentid_=copy.deepcopy(v.get("parentid"))id_=copy.deepcopy(v.get("id"))if dict1.get(parentid_)==None:dict1[parentid_]=[]dict1[parentid_].append(id_)childs=[]#msg.data.childs#填充第一层回帖for i in dict1.get(parent_id,[]):child1=copy.deepcopy(id_data_dict.get(i))#填充第二层回帖if dict1.get(i)!=None:#判断第二次是否还有回帖child2=[]for j in dict1.get(i):child3=copy.deepcopy(id_data_dict.get(j))id_=copy.deepcopy(child3.get("id"))if dict1.get(id_)!=None:#判断第三次是否还有回帖child3["childs"]=[]for k in dict1.get(id_):child4=copy.deepcopy(id_data_dict.get(k))id__=copy.deepcopy(child4.get("id"))if dict1.get(id__)!=None:#判断第四次是否还有回帖child4['childs']=[]for l in dict1.get(id__):child5=copy.deepcopy(id_data_dict.get(l))id___=copy.deepcopy(child5.get("id"))if dict1.get(id___)!=None:#判断第五次是否还有回帖child5['childs']=[]for m in dict1.get(id___):child6=copy.deepcopy(id_data_dict.get(m))id____=copy.deepcopy(child6.get("id"))if dict1.get(id____)!=None:#判断第六次是否还有回帖child6['childs']=[]child7=copy.deepcopy(id_data_dict.get(m))child7['childs']=[]for n in dict1.get(id____):child7['childs'].append(id_data_dict.get(n))child6['childs'].append(child7)child5['childs'].append(child6)child4["childs"].append(child5)child3["childs"].append(child4)child2.append(child3)child1['childs']=child2else:child1['childs']=Nonechilds.append(child1)print(childs)msg['data']['childs']=childsreturn JsonResponse(msg)