def order(request): if(request.method=='POST'): shopname = request.POST.get('shopname','NA') address = request.POST.get('address','NA') contact = request.POST.get('contact','NA') i1 = request.POST.get('i1',0) i2 = request.POST.get('i2',0) i3 = request.POST.get('i3',0) i4 = request.POST.get('i4',0) i5 = request.POST.get('i5',0) if not i1.isnumeric(): i1 = 0 if not i2.isnumeric(): i2 = 0 if not i3.isnumeric(): i3 = 0 if not i4.isnumeric(): i4 = 0 if not i5.isnumeric(): i5 = 0 message = request.POST.get('message','NA') order = Order(shopname=shopname, address=address, contact=contact, i1=i1, i2=i2, i3=i3, i4=i4, i5=i5, message=message) order.save() print("Order posted successfully") #return render(request, 'index.html') return redirect('home')
def new_order(request): if 'date' in request.POST: order_date = request.POST['date'] if 'pay_method' in request.POST: order_method = request.POST['pay_method'] if 'discount_rate' in request.POST: order_discount = request.POST['discount_rate'] if 'member_id' in request.POST: cid = request.POST['member_id'] order_member = Customer.objects.get(customer_id=cid) if 'product_id' in request.POST: pid = request.POST['product_id'] order_product = Product.objects.get(product_id=pid) if 'store_id' in request.POST: sid = request.POST['store_id'] order_store = Store.objects.get(store_id=sid) if 'shoe_size' in request.POST: order_size = request.POST['shoe_size'] o = Order(order_date=order_date, order_method=order_method, discount_rate=order_discount, customer_id=order_member, product_id=order_product, store_id=order_store, size=order_size) o.save() return render(request, '新增成功.html')
def index(request): products = Product.objects.order_by("id") if request.method == 'POST': #cfm is logged in form = OrderForm(request.POST) if form.is_valid(): #check time dt = datetime.today() d = date.today() date_form = form.cleaned_data['date'] if (date_form == d and (dt.hour > 11 or (dt.hour==11 and dt.minute>=30))): #overtime return redirect("/") for pdt in products: if pdt.name in request.POST: if int(form.cleaned_data[str(pdt.id)]) > 0: orderPdt = pdt.name orderQty = int(form.cleaned_data[str(pdt.id)]) else: request.session["global_message"] = "Please input amount" return redirect("/") currUser = request.user orderUser = UserProfile.objects.get(user=currUser.id) if orderUser.credit >= orderQty: orderUser.credit -= orderQty orderUser.save() newOrder = Order(user= orderUser, product=orderPdt, quantity=orderQty, date=date_form) newOrder.save() else: return redirect("/") #return not enough credits return redirect("/") else: form = OrderForm() currUser = request.user cust = UserProfile.objects.get(user=currUser.id) new = [] counter = 1 for field in form: if (counter == 1): counter += 1 else: new.append(field) zipped_data = list(zip(products, new)) context = {'zipped_data': zipped_data, 'form': form, 'cust':cust,} return render(request, 'meals/index.html', context) elif UserProfile.objects.filter(user=request.user.id).exists(): form = OrderForm() currUser = request.user cust = UserProfile.objects.get(user=currUser.id) new = [] counter = 1 for field in form: if (counter == 1): counter += 1 else: new.append(field) zipped_data = list(zip(products, new)) context = {'zipped_data': zipped_data, 'form': form, 'cust':cust,} return render(request, 'meals/index.html', context) else: #not login return redirect("/accounts/login")
def post(self, request, *args, **kwargs): prf_count = Profile.objects.filter(user_id=request.user.id).count() if prf_count > 0: order_list = json.loads(request.POST['data']) ids = [item['key'] for item in order_list] if Product.objects.filter(id__in=ids).count() == len(ids): new_order = Order( profile_id=Profile.objects.values('pk').get( user_id=request.user.id)['pk'], user_id=request.user.id, status_id=OrderStatus.objects.values('pk').get( name='Новый')['pk']) new_order.save() for item in order_list: prod_price = Product.objects.values('price').get( pk=item['key'])['price'] new_item = OrderItem( order_id=new_order.id, product_id=item['key'], count=float(item['value']['count']), price=float(prod_price), total_price=float(item['value']['count']) * prod_price) new_item.save() return JsonResponse({'status': 'OK'}) return JsonResponse({'status': 'WRONG_ORDER'}) else: return JsonResponse({'status': 'NO_ADDRESS'})
def checkout(request): if request.method == 'POST': if not request.session["cart"] or not request.session["cart"]["items"]: return HttpResponse("No items in cart.") new_order = Order(status=Order.QUEUED_FOR_PROCESSING, priority=request.POST.get('priority'), clinic=request.user.clinic) new_order.save() for item_id in request.session["cart"]["items"]: quantity = request.session["cart"]["items"][item_id] oi = OrderItem(order=new_order, item=Item.objects.get(pk=item_id), quantity=quantity) oi.save() # Empty the session request.session["cart"] = {"items": {}} return HttpResponse("Successfully created order.")
def confirm(request): if request.user.is_authenticated(): if request.method == "POST": try: car_id_list = request.POST.get('car_id') car_ids = car_id_list.split(',') for i in range(len(car_ids)): car = ShopCar.objects.get(car_id=car_ids[i], status=1) car.status = -1 car.save(update_fields=['status']) request.session['car_ids'] = car_ids # for i in range(len(car_ids)): # car_id = car_ids[i] # order_code = random.randint(0, 999999) # create_time = datetime.datetime.now(tz=datetime.timezone.utc) data = shop_count(request) data['status'] = 200 data['msg'] = 'success' return JsonResponse(data=data) except Exception as e: # 表示添加订单失败 data = shop_count(request) data['status'] = 400 data['msg'] = 'error' return JsonResponse(data=data) else: car_ids = request.session['car_ids'] for i in range(len(car_ids)): car_id = car_ids[i] order_code = random.randint(0, 99999999) create_date = datetime.datetime.now() order = Order(order_code=order_code, create_date=create_date, status=2, uid_id=request.user.id, car_id_id=car_id) order.save() car_id = ShopCar.objects.filter(car_id__in=car_ids) addresses = UserAddress.objects.filter(uid=request.user.id) return render(request, 'order.html', { 'car_id': car_id, 'addresses': addresses }) else: return redirect('/user/login/')
def checkout(request): if request.method == "POST": items_json = request.POST.get('itemsJson', '') name = request.POST.get('name') amount = request.POST.get('amount') email = request.POST.get('email') phone = request.POST.get('phone') address = request.POST.get('address') city = request.POST.get('city') state = request.POST.get('state') zip_code = request.POST.get('zip_code') order= Order(amount=amount,items_json=items_json,name=name, email=email, phone=phone, address=address,city=city,zip_code=zip_code,state=state) order.save() thank = True id = order.order_id return render(request,"checkout.html", {'thank': thank, 'id': id}) return render(request, "checkout.html")
def checkout(request): if request.method == 'POST': address = request.POST.get('address') phone = request.POST.get('phone') user = request.session.get('user_id') cart = request.session.get('cart') items = Item.get_product_by_id(list(cart.keys())) for item in items: order = Order(user=User(id=user), item=item, price=item.price, quantity=cart.get(str(item.id)), address=address, phone=phone) order.save() messages.success(request, "Order Placed") request.session['cart'] = {} return redirect('/cart')
def validate(request): usercart = 0 for panier in Cart.objects.all(): if panier.user == request.user: usercart = panier if usercart != 0: itemlist = [] for item in CartItem.objects.all(): if item.cart == usercart: itemlist.append(item) if len(itemlist) > 0: order = Order(user=request.user) order.save() for item in itemlist: oit = OrderItem(quantity=item.quantity, product=item.product, order=order, price=item.price) oit.save() usercart.delete() return redirect("../commandes")
def new_order(request, customer_id): c_id = int(customer_id) customer_obj = Customer.objects.filter(id=c_id) cats = Category.objects.filter(is_active=True).values_list('name', flat=True) if len(customer_obj) == 1: customer_obj = customer_obj[0] if request.method == 'POST': kg = float(request.POST.get('kg')) price_json = OrderedDict() all_price = Price.objects.all().order_by('kg') for each_price in all_price: price_json[str(each_price.kg)] = each_price.cost price_json = OrderedDict(sorted(price_json.items())) if kg < 0: return render( request, 'new_order.html', { 'customer_obj': customer_obj, 'price_json': json.dumps(price_json), 'message_title': 'Error', 'message_type': 'error', 'message': 'Kg should be greater than 0', 'category': [cats[i:i + 2] for i in range(0, len(cats), 2)] }) # current_price = Price.objects.order_by('-kg').filter(kg__lte=kg)[:1][0] current_price = float(request.POST.get('price')) print(current_price) order_obj = Order(customer=customer_obj, kg=kg, received_date=datetime.datetime.now(), price=current_price, status=1) order_obj.save() if request.POST.get('selected') == 'ind_kg': for each in request.POST: if each.__contains__('cloth_'): each_id = each.split('cloth_')[1] cat_obj = Category.objects.get_or_create( name=request.POST.get(each), is_active=True)[0] order_details = OrderDetail( order=order_obj, category=cat_obj, count=int(request.POST.get('qty_' + each_id))) order_details.save() order_obj.status = 2 order_obj.save() return render( request, 'new_order.html', { 'customer_obj': customer_obj, 'price_json': json.dumps(price_json), 'message_type': 'success', 'message_title': 'Success', 'swal_redirect': '/', 'message': 'Order registered for customer ' + customer_obj.name, 'category': [cats[i:i + 2] for i in range(0, len(cats), 2)] }) else: all_price = Price.objects.all().order_by('kg') price_json = {} for each_price in all_price: price_json[str(each_price.kg)] = each_price.cost return render( request, 'new_order.html', { 'customer_obj': customer_obj, 'price_json': json.dumps(price_json), 'category': [cats[i:i + 2] for i in range(0, len(cats), 2)] }) else: return HttpResponse('No objects found with that id')
def ordercreate(request): totail = 0 # 商品总价 totail_num = 0 for i in request.session['order_add']: totail += i['num'] * i['price'] totail_num += i['num'] data = request.POST print(data) if data.get('consignee') and data.get('address') and data.get( 'phone') and data.get('code'): try: # 1. 添加订单数据信息 oi = Order() # 添加订单数据 oi.total_price = totail oi.total_number = totail_num oi.addcode = data.get('code') # 收获邮箱 oi.addname = data.get('consignee') # 收获人 oi.addphone = data.get('consignee') # 收获手机号 oi.address = data.get('address') # 收获地址 oi.uid = Users.objects.get( id=request.session['login_users']['user_id']) # 订单用户 oi.status = 1 # 订单状态 oi.save() # 保存数据 # 2, 添加订单详情 # print(request.session['order_add']) for i in request.session['order_add']: order_info_add = OrderInfo() order_info_add.num = i.get('num') # 商品数量 order_info_add.price = i.get('price') # 商品单价 order_info_add.orderid = oi order_info_add.gid = Goods.objects.get(id=i.get('id')) order_info_add.save() del request.session['cart'][str(i.get('id'))] if request.session.get('order_add'): del request.session['order_add'] return HttpResponse( '<script>alert("下单成功, 请支付");location.href="/buy/%s"</script>' % oi.id) except: return HttpResponse( '<script>alert("订单信息错误, 请重新添加");location.href="/orderadd/"</script>' ) return HttpResponse( '<script>alert("没有填写收获信息,请重新填写");location.href="/orderadd/"</script>')
def save_order(): """保存订单(生成订单接口)""" user_id = g.user_id # 获取参数 order_data = request.get_json() if not order_data: return jsonify(errno=RET.PARAMERR, errmsg="参数错误") house_id = order_data.get("house_id") # 预定的房屋编号 start_date_str = order_data.get("start_date") # 预定的起始时间 end_date_str = order_data.get("end_date") # 预定的结束时间 # 参数检查 if not all([house_id, start_date_str, end_date_str]): return jsonify(errno=RET.PARAMERR, errmsg="参数错误") # 日期检查 try: # 将请求的时间参数字符串转换为datatime类型 start_date = datetime.strptime(start_date_str, "%Y-%m-%d") end_date = datetime.strptime(end_date_str, "%Y-%m-%d") assert start_date <= end_date # 断言,条件为false的时候触发异常 days = (end_date - start_date).days + 1 except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.PARAMERR, errmsg="日期格式错误") # 查询房屋是否存在 try: house = House.query.get(house_id) except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.DBERR, errmsg="获取房屋信息失败") if not house: return jsonify(errno=RET.NODATA, errmsg="房屋不存在") # 预定的房屋是否是房东自己 if user_id == house.user_id: return jsonify(errno=RET.ROLEERR, errmsg="不能预定自己的房屋") # 确保用户预定的时间内,房屋没有被别人预定 try: # 查询时间冲突的订单数 count = Order.query.filter(Order.house_id == house_id, Order.begin_date <= end_date, Order.end_date >= start_date).count() except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.DBERR, errmsg="检查出错,请稍候重试") # 只要存在冲突订单就说明不能再预定了 if count > 0: return jsonify(errno=RET.DATAERR, errmsg="房屋已被预定") # 订单总额 amount = days * house.price # 保存订单数据 order = Order(house_id=house_id, user_id=user_id, begin_date=start_date, end_date=end_date, days=days, house_price=house.price, amount=amount) try: db.session.add(Order) db.session.commit() except Exception as e: current_app.logger.error(e) db.session.rollback() return jsonify(errno=RET.DBERR, errmsg="保存订单失败") return jsonify(errno=RET.OK, errmsg="OK", data={"order_id": order.id})
def order_view(request): user = request.session.get('user_id') orders = Order.get_order_by_user(user) orders = orders.reverse() return render(request, 'home/order.html', {'orders': orders})
def Settlement(request): ''' 下单结算页 [填写并核对订单信息] 只适合单种商品下单,多种商品下单无法计算价格 :param request: :return: ''' if request.method == 'GET': wareid = request.GET.get('id') purchase = request.GET.get('purchase') duration = request.GET.get('duration') number = request.GET.get('number') print('purchase', purchase) username = request.user.username users = models.User.objects.get(username=username) add = Address.objects.filter(key=users, defaule=True) if not add: add = Address.objects.filter(key=users) pass if add: add = add[0] ware = models.WareApp.objects.filter(id=wareid) lease_or = models.Lease.objects.get(ware_key=ware[0], id=purchase, select=1) # select 1 购买/select 0 租赁 money = float(lease_or.money) # '总金额' logger.i('总金额', money) defaule = False # 是否是国采登录用户 defaule_money = 0 # 国采用户打折 try: U = models.User.objects.get(username=request.user.username) if U.usercode: defaule = True defaule_money = 0 pass except: defaule = False pass try: classify = models.WareAppPrefix.objects.get(wareApp_key=ware) except: classify = None dismoney = 0 number_money = float(money) * float(number) if classify and defaule: logger.i('优惠率', classify, defaule) theress = classify.classifythere_key discon = Discount.objects.get(classif_there=theress) if int(number_money) <= 100000: # a1 dismoney = discon.a1 defaule_money = (100 - float(dismoney)) / 100 * float(money) logger.i('int(number_money) <= 100000', defaule_money, money) pass elif 100000 < int(number_money) and int(number_money) <= 300000: # a2 dismoney = discon.a2 defaule_money = (100 - float(dismoney)) / 100 * float(money) logger.i('100000 < int(number_money) and int(number_money) <= 300000', defaule_money) pass elif 300000 < int(number_money) and int(number_money) <= 600000: # a3 dismoney = discon.a3 defaule_money = (100 - float(dismoney)) / 100 * float(money) logger.i('300000 < int(number_money) and int(number_money) <= 600000', defaule_money) pass elif 600000 < int(number_money) and int(number_money) < 1000000: # a4 dismoney = discon.a4 defaule_money = (100 - float(dismoney)) / 100 * float(money) logger.i('600000 < int(number_money) and int(number_money) <= 1000000', defaule_money) elif float(number_money) >= 1000000: return error_(request, code=403, title='订单错误', page='Order error', content='单笔订单不可大于等于100万人民币') pass total = float(number) * float(money) total_defaule_money = float(number) * float(defaule_money) money = Decimal(money).quantize(Decimal('0.00')) total = Decimal(total).quantize(Decimal('0.00')) total_defaule_money = Decimal(total_defaule_money).quantize(Decimal('0.00')) defaule_money = Decimal(defaule_money).quantize(Decimal('0.00')) logger.i('单价', money) logger.i('单价优惠', defaule_money) logger.i('总优惠', total_defaule_money) try: invs = Invoices.objects.get(key=users) logger.i(invs.stype) inv = { 'stype': invs.stype, 'content': invs.content, 'taxpayer': invs.taxpayer, 'phone': invs.phone, 'email': invs.email, 'head': invs.head, 'unitName': invs.unitName, 'registeredAddress': invs.registeredAddress, 'registeredTelephone': invs.registeredTelephone, 'accountOpening': invs.accountOpening, 'account': invs.account } except: inv = {} pass moneytable = [] for i in Discount.objects.filter(defaule=True): moneytable.append({ 'id': i.id, 'name': i.classif_there.name, 'a1': i.a1.to_integral, 'a2': i.a2.to_integral, 'a3': i.a3.to_integral, 'a4': i.a4.to_integral }) content = { 'moneytable': moneytable, 'inv': inv, 'address': add, 'number': number, 'ware': ware, 'total': total, 'dismoney': dismoney, 'defaule': defaule, 'money': money, 'defaule_money': defaule_money, 'total_defaule_money': total_defaule_money, 'wareid': wareid, 'select': 1, 'purchase': purchase, 'duration': duration, } return render(request, 'defaule/home/settlement.html', content) if request.method == 'POST': username = request.user.username wareid = request.POST.get('id') purchase = request.POST.get('purchase') duration = request.POST.get('duration') number = request.POST.get('number') invoices = request.POST.get('invoices') ''' 创建订单 :param request: :return: ''' address = request.POST.get('address') remark = request.POST.get('remark') # 订单备注 paymethod = request.POST.get('paymethod') # '支付方式' logger.i('wareid', wareid) ware = models.WareApp.objects.get(id=wareid) logger.i('WareApp', ware) user = models.User.objects.get(username=username) lease_or = models.Lease.objects.get(ware_key=ware, id=purchase, select=1) # select 1 购买/select 0 租赁 money = float(lease_or.money) # '总金额' duration_or = None # if select == '0': # lease_or = models.Lease.objects.get(ware_key=ware, id=purchase, select=select) # select 1 购买/select 0 租赁 # duration_or = models.Duration.objects.get(ware_key=ware, id=duration) # 租赁配置 - 分类信息[租赁时间] # money = float(lease_or.money) + float(duration_or.money) # '总金额' # elif select == '1': # lease_or = models.Lease.objects.get(ware_key=ware, id=purchase, select=select) # select 1 购买/select 0 租赁 # money = float(lease_or.money) # '总金额' # duration_or = None # else: # lease_or, duration_or = None, None # money = -1 # pass # images = models.images.objects.filter(key=ware)[:1].get().image add = Address.objects.filter(id=address, key=user) if add: province = add[0].province city = add[0].city area = add[0].area deliveryaddress = '{}'.format(add[0].consigneeAddress) linkman = add[0].consigneeName # userinfo.name # 购买人姓名 linkmobile = add[0].consigneeMobile # userinfo.phone # 购买人联系方式 else: return redirect(reverse('home:address')) '''''' defaule = False # 是否是国采登录用户 defaule_money = 0 # 国采用户打折 orderid = _order_num(package_id=ware.id, user_id=user.id) # '创建订单号' suborderid = orderid # 子订单号 try: U = models.User.objects.get(username=request.user.username) if U.usercode: defaule = True defaule_money = 0 pass except: defaule = False pass try: classify = models.WareAppPrefix.objects.get(wareApp_key=ware) except: classify = None dismoney = 0 number_money = float(money) * float(number) if classify and defaule: theress = classify.classifythere_key discon = Discount.objects.get(classif_there=theress) if float(number_money) <= 100000: # a1 dismoney = discon.a1 defaule_money = (100 - float(discon.a1)) / 100 * float(money) logger.i('float(number_money) <= 100000', defaule_money) pass elif 100000 < float(number_money) and float(number_money) <= 300000: # a2 dismoney = discon.a2 defaule_money = (100 - float(discon.a2)) / 100 * float(money) logger.i('100000 < float(number_money) and float(number_money) <= 300000', defaule_money) pass elif 300000 < float(number_money) and float(number_money) <= 600000: # a3 dismoney = discon.a3 defaule_money = (100 - float(discon.a3)) / 100 * float(money) logger.i('300000 < float(number_money) and float(number_money) <= 600000', defaule_money) pass elif 600000 < float(number_money) and float(number_money) <= 1000000: # a4 dismoney = discon.a4 defaule_money = (100 - float(discon.a4)) / 100 * float(money) logger.i('600000 < float(number_money) and float(number_money) < 1000000', defaule_money) elif float(number_money) >= 1000000: return error_(request, code=403, title='订单错误', page='Order error', content='单笔订单不可大于等于100万人民币') pass total_defaule_money = float(number) * float(defaule_money) '''''' total = float(total_defaule_money) # 总订单价钱 Subtotal = total # 子订单总价 ############# price = defaule_money # 商品单价 originalprice = money # 订单原价 '''''' logger.i('订单原价: ', money) logger.i('优惠率', dismoney) logger.i('商品单价优惠: ', defaule_money) logger.i('总订单优惠: ', total_defaule_money) else: total = float(number) * float(money) # 总订单价钱 '''''' Subtotal = total # 子订单总价 ############# price = float(money) # 商品单价 originalprice = float(money) # 订单原价 '''''' money = Decimal(money).quantize(Decimal('0.00')) total = Decimal(total).quantize(Decimal('0.00')) Subtotal = Decimal(Subtotal).quantize(Decimal('0.00')) price = Decimal(price).quantize(Decimal('0.00')) originalprice = Decimal(originalprice).quantize(Decimal('0.00')) logger.i('订单原价: ', money) logger.i('商品单价: ', money) logger.i('总订单价: ', total) spu = ware.name # '细化到商品' goodsclassguid = goodsclassname = goodsbrandname = sku = model = '' if defaule: try: guid = Gusid.objects.get(key=classify.classifythere_key) except: return error_(request, content='商品目录ID不完整,或未分类', code=403) try: per = parameter.objects.get(key=ware) sku = '{} {} {}'.format(per.model, per.productType, per.colorType) # '细化到规格、型号' model = '{}'.format(per.model) # '商品型号、规格' goodsbrandname = per.brands # '品牌名称' goodsclassguid = guid.guid # '商品目录ID 枚举值对照表' goodsclassname = guid.name # '商品类别名' except: return error_(request, content='商品参数不完整,最少具备的参数: 产品型号, 产品类型, 颜色类型') usercode = user.usercode url = '/app/details/{}/'.format(wareid) logger.i('商品目录ID', goodsclassguid) logger.i('商品类别名', goodsclassname) logger.i('品牌名称', goodsbrandname) try: inv = Invoices.objects.get(key=user) except: inv = None if usercode: o = Order( name='{}({})'.format(ware.name, lease_or.name), orderid=orderid, paymethod=paymethod, total=total, money=total, number=number, province=province, city=city, area=area, invoice=invoices, linkman=linkman, linkmobile=linkmobile, deliveryaddress=deliveryaddress, remark=remark, usercode=usercode, createtime=datetimenow(), images=ware.image, url=url, key_inv=inv, key=user ) else: o = Order( name='{}({})'.format(ware.name, lease_or.name), orderid=orderid, paymethod=paymethod, total=total, number=number, province=province, city=city, area=area, invoice=invoices, linkman=linkman, linkmobile=linkmobile, deliveryaddress=deliveryaddress, remark=remark, createtime=datetimenow(), images=ware.image, url=url, key_inv=inv, key=user ) o.save() s = Suborderlist( suborderid=suborderid, url=url, total=Subtotal, key=o ) s.save() Goodslist( goodsname='{}({})'.format(ware.name, lease_or.name), goodsid=ware.id, spu=spu, sku=sku, model=model, goodsclassguid=goodsclassguid, goodsclassname=goodsclassname, goodsbrandname=goodsbrandname, qty=number, total=total, price=price, originalprice=originalprice, imgurl=ware.image, goodsurl=url, key=s ).save() Logistics( info='您提交了订单,请等待卖家系统确认', time=datetimenow(), username='******', key=o ).save() o.lease_or = lease_or if paymethod == '1' or paymethod == '2' or paymethod == '3' or paymethod == '4' or paymethod == '9': o.state = 2 pass o.save() if usercode: auto = AutoRsaGraph(usercode=usercode, orderid=orderid) order_create = auto.order_create() order_logistics = auto.order_logistics() logger.i('央采 创建订单', order_create) logger.i('央采 物流推送接口', order_logistics) else: logger.i('没有usercode') pass return HttpResponseRedirect('/home/success/?orderId={}'.format(orderid)) pass pass
def orderproduct(request, id): #rezervasyon url = request.META.get("HTTP_REFERER") # gelinen url category = Category.objects.all() setting = Setting.objects.get(pk=1) current_user = request.user product = Car.objects.get(id=id) total = Calculate.objects.all().order_by('-id')[0].day * product.price if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): # form geçerli ise data = Order() data.first_name = form.cleaned_data[ 'first_name'] # formdan veriyi getiriyor data.last_name = form.cleaned_data[ 'last_name'] # formdan veriyi getiriyor data.city = form.cleaned_data['city'] # formdan veriyi getiriyor data.phone = form.cleaned_data['phone'] # formdan veriyi getiriyor data.date_start = Calculate.objects.all().order_by( '-id')[0].date_start data.date_end = Calculate.objects.all().order_by('-id')[0].date_end data.quatity = Calculate.objects.all().order_by('-id')[0].day data.address = form.cleaned_data['address'] data.country = form.cleaned_data['country'] data.user_id = current_user.id data.car_id = id data.total = total data.ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(5).upper() data.code = ordercode data.save() orderproduct = OrderProduct() orderproduct.user_id = current_user.id product.amount = product.amount - 1 product.save() Calculate.objects.all().order_by('-id')[0].delete() messages.success(request, "Rezervasyonunuz Yapıldı\nCode %s" % ordercode) return HttpResponseRedirect(url) # return HttpResponseRedirect("/") else: messages.warning(request, form.errors) return HttpResponseRedirect(url) form = OrderForm() profile = UserProfile.objects.get(user_id=current_user.id) context = { 'category': category, 'total': total, 'form': form, 'profile': profile, 'setting': setting } return render(request, 'Order_Form.html', context)