def orderproduct(request): category = Category.objects.all() current_user = request.user schopcart = ShopCart.objects.filter(user_id=current_user.id) total = 0 for rs in schopcart: total += rs.product.price * rs.quantity if request.method == 'POST': # if there is a post form = OrderForm(request.POST) # return HttpResponse(request.POST.items()) if form.is_valid(): # Send Credit card to bank, If the bank responds ok, continue, if not, show the error # .............. data = Order() data.first_name = form.cleaned_data['first_name'] # get product quantity from form data.last_name = form.cleaned_data['last_name'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.phone = form.cleaned_data['phone'] data.user_id = current_user.id data.total = total data.ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(5).upper() # random cod data.code = ordercode data.save() # schopcart = ShopCart.objects.filter(user_id=current_user.id) for rs in schopcart: detail = OrderProduct() detail.order_id = data.id # Order Id detail.product_id = rs.product_id detail.user_id = current_user.id detail.quantity = rs.quantity detail.price = rs.product.price detail.amount = rs.amount detail.save() # ***Reduce quantity of sold product from Amount of Product product = Product.objects.get(id=rs.product_id) product.amount -= rs.quantity product.save() ShopCart.objects.filter(user_id=current_user.id).delete() # Clear & Delete shopcart request.session['cart_items'] = 0 messages.success(request, "Your Order has been completed. Thank you ") return render(request, 'Order_Completed.html', {'ordercode': ordercode, 'category': category}) else: messages.warning(request, form.errors) return HttpResponseRedirect("/order/orderproduct") form = OrderForm() profile = UserProfile.objects.get(user_id=current_user.id) context = {'schopcart': schopcart, 'category': category, 'total': total, 'form': form, 'profile': profile, } return render(request, 'Order_Form.html', context)
def productOrder(request): category = Category.objects.all() current_user = request.user basket = CustomerBasket.objects.filter(user_id = current_user.id) total = 0 for rs in basket: total += rs.product.price * rs.quantity if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): data = Order() data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.phone = form.cleaned_data['phone'] data.user_id = current_user.id data.total = total data.ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(5).upper() data.code = ordercode data.save() basket = CustomerBasket.objects.filter(user_id=current_user.id) for rs in basket: detail = OrderProduct() detail.order_id = data.id detail.product_id = rs.product_id detail.user_id = current_user.id detail.quantity = rs.quantity product = Product.objects.get(id=rs.product_id) product.amount -= rs.quantity product.save() detail.price = rs.product.price detail.amount = rs.amount detail.save() CustomerBasket.objects.filter(user_id = current_user.id).delete() request.session['cart_items']=0 messages.success(request, "Sipariş tamamlandı!") return render(request, 'shop-basket.html',{'ordercode':ordercode,'category':category}) else: messages.warning(request, form.errors) return HttpResponseRedirect("/order/orderproduct") form = OrderForm() profile = UserProfile.objects.get(user_id = current_user.id) context = { 'basket':basket, 'total':total, 'form':form, 'profile':profile } return render(request, 'shop-checkout1.html', context)
def checkout_transaction(request): cart = request.user.cart items = cart.cartitem_set.all() with transaction.atomic(): try: # Check if sufficient inventory for whole order, else raise error before creating order for item in items: p = Product.objects.get(name=item.product.name) if item.quantity > p.inventory: raise IntegrityError new_order = Order(user=request.user) new_order.save() for item in items: p = Product.objects.get(name=item.product.name) order_product = OrderProduct(product=item.product, order=new_order, quantity=item.quantity, cost=item.product.price) order_product.save() p.inventory = p.inventory - item.quantity p.save() cart.delete() except IntegrityError: messages.warning(request, "Transaction failed, not enough in inventory!") return HttpResponseRedirect(reverse('profile_cart')) return HttpResponseRedirect( reverse('profile_orderdetail', args=(new_order.pk, )))
def orderproduct(request): current_user = request.user shopcart = ShopCart.objects.filter(user_id=current_user.id) total = 0 count = 0 for rs in shopcart: total += rs.product.price * rs.quantity count += rs.quantity if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): data = Order() data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.phone = form.cleaned_data['phone'] data.user_id = current_user.id data.total = total data.ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(5).upper() data.code = ordercode data.save() for rs in shopcart: detail = OrderProduct() detail.order_id = data.id detail.product_id = rs.product_id detail.user_id = current_user.id detail.quantity = rs.quantity detail.price = rs.product.price detail.amount = rs.amount detail.save() product = Product.objects.get(id=rs.product_id) product.amount -= rs.quantity product.count_sold += 1 product.save() ShopCart.objects.filter(user_id=current_user.id).delete() request.session['cart_item'] = 0 messages.success(request, 'Your order has been completed.') return render(request, 'Order_Completed.html', {'ordercode': ordercode}) else: messages.warning(request, form.errors) return HttpResponseRedirect('/order/orderproduct') form = OrderForm() profile = UserProfile.objects.get(user_id=current_user.id) context = { 'shopcart': shopcart, 'total': total, 'form': form, 'profile': profile, } return render(request, 'order_form.html', context)
def orderproduct(request): category = Category.objects.all() current_user = request.user schopcart = ShopCart.objects.filter(user_id=current_user) total = 0 for rs in schopcart: total += rs.product.price * rs.quantity if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): data = Order() data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.country=form.cleaned_data['country'] data.phone = form.cleaned_data['phone'] data.user_id = current_user.id data.total = total data.ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(5).upper() data.code = ordercode data.save() schopcart = ShopCart.objects.filter(user_id = current_user.id) for rs in schopcart: detail = OrderProduct() detail.order_id =data.id detail.product_id =rs.product_id detail.user_id = current_user.id detail.quantity = rs.quantity product = Product.objects.get(id = rs.product_id) product.amount = rs.quantity product.save() detail.price = rs.product.price detail.amount = rs.amount detail.save() ShopCart.objects.filter(user_id=current_user.id).delete() request.session['cart_items'] =0 messages.success(request,"Siparişiniz verildi, Teşekkürler") return render(request,'order_Completed.html',{'ordercode':ordercode,'category':category}) else: messages.error(request,form.errors) return HttpResponseRedirect("/order/orderproduct") form = OrderForm() profile = UserProfile.objects.get(user_id = current_user.id) context = {'schopcart':schopcart, 'category':category, 'total':total, 'form':form, 'profile':profile,} return render(request,'Order_Form.html',context)
def orderproduct(request): category = Category.objects.all() current_user = request.user shopcart = ShopCart.objects.filter(user_id=current_user) total = 0 for rs in shopcart: total += rs.product.price * rs.quantity if request.method == 'POST': form = OrderForm() if form.is_valid(): data = Order() data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.phone = form.cleaned_data['phone'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.country = form.cleaned_data['country'] data.user_id = current_user.id data.ip = request.META('REMOTE_ADDR') ordercode = get_random_string(12).upper() data.code = ordercode data.save() shopcart = ShopCart.objects.filter(user_id=current_user.id) for rs in shopcart: detail = OrderProduct() detail.order_id = data.id detail.product = rs.product_id detail.user_id = rs.user_id detail.quantity = rs.quantity detail.price = rs.product.price detail.amount = rs.product.amount detail.save() product = Product.objects.get(rs.product_id) product.amount -= rs.quantity product.save() ShopCart.objects.filter(user_id=current_user.id).delete() request.session['cart_item'] = 0 messages.success(request, "SIzning buyurtmangiz qabul qilindi!") return render(request, 'ordercomplete.html', { 'ordercode': ordercode, 'category': category}) else: messages.warning(request, form.errors) return HttpResponseRedirect('/order/orderproduct') form = OrderForm shopcart = ShopCart.objects.filter(user_id=current_user.id) profile = UserProfile.objects.filter(user_id=current_user.id) context = { 'shopcart': shopcart, 'category': category, 'total': total, 'profile': profile, 'form': form, } return HttpResponseRedirect(request, 'orderproduct.html', context)
def buyProduct(request, product_id): amount = request.POST.get('amount', 1) try: product = Product.objects.get(id=product_id) order = Order() order.client = request.META["REMOTE_ADDR"] order.details = "is buying the product " + product.name + " in MINITRADE" order.total = product.price * int(amount) order.status = "created" order.save() orderProduct = OrderProduct() orderProduct.product = product orderProduct.order = order orderProduct.amount = amount orderProduct.total = product.price * int(amount) orderProduct.save() callback_url = "https://{0}/finish_buy/{1}/".format(request.get_host(), order.id) response = createPayRequest(order, callback_url) order.token = response['token'] order.status = response['status'] order.save() return HttpResponse(json.dumps({ "url": response['url'] }), status=200) except Exception as e: # import traceback # traceback.print_exc() return HttpResponse(json.dumps({ "error": str(e), "message": "The transaction could not be created!" }), status=500)
def post(self, request, *args, **kwargs): current_user = request.user shopcart = ShopCart.objects.filter(user_id=self.request.user.id) total = 0 count = 0 for rs in shopcart: total += rs.product.price * rs.quantity count += rs.quantity form = OrderPaymentForm(request.POST) if form.is_valid(): data = Order() data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.phone = form.cleaned_data['phone'] data.user_id = current_user.id data.total = total data.payment_option = form.cleaned_data['payment_option'] data.save() for rs in shopcart: detail = OrderProduct() detail.order_id = data.id detail.product_id = rs.product_id detail.user_id = current_user.id detail.quantity = rs.quantity detail.price = rs.product.price detail.amount = rs.amount detail.save() product = Product.objects.get(id=rs.product_id) product.count_sold += 1 product.amount -= rs.quantity product.save() if data.payment_option == "S": return redirect('payment', payment_option="stripe") if data.payment_option == "P": return redirect('payment', payment_option="paypal") messages.info(self.request, "Invalid payment option") return redirect('checkout') else: return redirect('checkout')
def post(self, request, order_id, product_id): """ 주문을 생성합니다. order_id : 입력받은 order_id를 이용하여 검증된 유저의 장바구니 여부를 확인합니다. product_id : 개별적으로 주문을하고 장바구니에 담길 상품의 id입니다. """ data = json.loads(request.body) user_id = request.userid try: if Order.objects.filter(username_id=user_id).exists(): user_address = User.objects.get(id=user_id).address if user_address: if Order.objects.filter(id=order_id).exists(): if Product.objects.filter(id=product_id).exists(): order_id = Order.objects.get(id=order_id) product_id = Product.objects.get(id=product_id) new_order = OrderProduct(order=order_id, product=product_id, quantity=data['quantity']) new_order.save() return JsonResponse({'message': "장바구니에 담겼습니다"}, status=200) return JsonResponse({'message': '해당 상품은 존재하지 않습니다'}, status=400) return JsonResponse({'message': '주소를 등록해주세요'}, status=400) else: new_order = Order(username_id=user_id) new_order.save() return JsonResponse({'message': '장바구니가 생성됬습니다'}, status=200) except KeyError: return JsonResponse({'error': '올바르지 않은 키 값'}, status=400)
def checkout(request): current_user = request.user shopcart = ShopCart.objects.filter(user_id = current_user.id) total = 0 q = 0 for s in shopcart: total += s.product.price * s.quantity q += s.quantity setting = Setting.objects.all() catagories = ProductCategories.objects.all() data = Order() if request.method == "POST": data.full_name = request.POST.get("name") data.address = request.POST.get("address") data.city = request.POST.get("city") data.country = request.POST.get("country") data.phone = request.POST.get("tel") data.user_id = current_user.id data.ip = request.META.get('REMOTE_ADDR') data.total = total orderCode = get_random_string(5).upper() data.code = orderCode data.save() for rs in shopcart: detail = OrderProduct() detail.order_id = data.id detail.product_id = rs.product_id detail.user_id = current_user.id detail.quantity = rs.quantity detail.price = rs.product.price detail.amount = total detail.save() ShopCart.objects.filter(user_id=current_user.id).delete()#clear and delete shopcart messages.success(request,"Your order has been completed. Thank you.") return render(request, 'order_Completed.html',{'orderCode':orderCode,'category':catagories}) context = { "catagories":catagories, "setting":setting, 'total':total, 'q':q, } return render(request, 'checkout.html',context=context)
def order(request, id): if request.method == "POST": current_user = request.user whole_total = 0 shopcart = ShopCart.objects.filter(user_id=current_user.id) for each in shopcart: whole_total += each.price * each.quantity # add the total price of cart items #for order model order = Order() order.user = current_user order.code = "oppps" order.first_name = request.POST.get('first_name') order.last_name = request.POST.get('last_name') order.phone = request.POST.get('phone') order.email = request.POST.get('email') order.address = request.POST.get('address') order.address_desc = request.POST.get('address_desc') order.city = request.POST.get('city') order.total = whole_total order.status = request.POST.get('status') order.save() # for order product model for items in shopcart: orderproduct = OrderProduct() orderproduct.user = current_user # orderproduct.user = items.user orderproduct.order = Order.objects.get(id=order.id) # cart_items = ShopCart.objects.filter(user_id= current_user.id) # orderproduct.product = Product.objects.get(id = items.product.id) orderproduct.product = items.product orderproduct.quantity = items.quantity orderproduct.amount = 5 orderproduct.price = 1200 orderproduct.save() url = request.META.get('HTTP_REFERER') return HttpResponseRedirect(url)
def orderproduct(request, id): setting = Setting.objects.get(pk=1) category = Category.objects.all() product = Product.objects.get(pk=id) current_user = request.user total = product.price if request.method == 'POST': # if there is a post form = OrderForm(request.POST) if form.is_valid(): data = Order() data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.phone = form.cleaned_data['phone'] data.user_id = current_user.id data.ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(5).upper() data.code = ordercode data.save() orderproduct = OrderProduct() orderproduct.order = data orderproduct.price = total orderproduct.user = current_user orderproduct.product = product orderproduct.save() messages.success(request, "Your Order has been completed. Thank you ") return render(request, 'Order_Completed.html', {'ordercode': ordercode, 'category': category, 'setting': setting}) else: messages.warning(request, form.errors) return HttpResponseRedirect("/order/orderproduct/" + str(id)) form = OrderForm() profile = UserProfile.objects.get(user_id=current_user.id) context = {'category': category, 'form': form, 'total': total, 'profile': profile, 'product': product, 'setting': setting, } return render(request, 'Order_Form.html', context)
def create(self, validated_data): carts = validated_data['carts'] product_ids = [cart.product_option.product_id for cart in carts] request_user = self.context['request'].user with transaction.atomic(): order = Order.objects.create( user=request_user, order_uid=self.create_order_uid(), shipping_price=self.get_calculated_products_shipping_price( product_ids), shipping_address=validated_data['shipping_address'], shipping_request_note=validated_data['shipping_request_note'], is_paid=False, ) order_products = [ OrderProduct( user=request_user, cart=cart, product_option=cart.product_option, order=order, product_price=cart.product_option.product.price, ordered_quantity=cart.quantity, ordered_price=cart.product_option.product.price * cart.quantity, status=OrderProduct.STATUS_CHOICE.PENDING, ) for cart in carts ] OrderProduct.objects.bulk_create(order_products) Payment.objects.create(order=order, pay_price=order.shipping_price + sum([ order_product.ordered_price for order_product in order_products ]), pay_method=getattr( Payment.PAY_METHOD_CHOICE, validated_data['pay_method'])) return order
def order_create(user: User, items: list) -> Order: order = Order.objects.create(user=user) try: order_products = [] for item in items: product = Product.objects.get(id=item.get('product')) if product.quantity < item.get('quantity'): order.delete() raise ValidationError( 'There are not enough {product} in stock. Only have {quantity}'.format(product=product.name, quantity=product.quantity)) order_products.append(OrderProduct(order=order, product=product, quantity=item.get('quantity'))) except Product.DoesNotExist: order.delete() raise ValidationError('One or more product does not exist') OrderProduct.objects.bulk_create(order_products) return order
def post(self, request): try: data = json.loads(request.body) user_id = request.user.id chosen_products = data['chosen_product'] target_cart, flag = Order.objects.get_or_create(user_id=user_id, order_status_id=1) target_options = [ chosen_products[i]["product_option_id"] for i in range(0, len(chosen_products)) ] for option in target_options: if OrderProduct.objects.filter(order=target_cart.id, product_option=option).exists(): return JsonResponse({'message': 'ALREADY_EXISTS'}, status=409) target_products = [ ProductOption.objects.get(id=target_options[i]).product_id for i in range(0, len(target_options)) ] target_amount = [ chosen_products[i]['amount'] for i in range(0, len(chosen_products)) ] for j in range(0, len(target_options)): OrderProduct(product_amount=target_amount[j], order_id=target_cart.id, product_id=target_products[j], product_option_id=target_options[j]).save() return JsonResponse({"message": "PRODUCT_ADDED"}, status=201) except KeyError: return JsonResponse({"message": "KEY_ERROR"}, status=400)
def create(self, validated_data): validated_data['creator_id'] = self.context['request'].user order_positions_data = validated_data.pop('order_positions') total_price = 0 for order_position_data in order_positions_data: product = Product.objects.filter( id=order_position_data['product'].id).first() total_price += product.price * order_position_data['quantity'] validated_data['total_price'] = total_price order = super().create(validated_data) raw_order_positions = [] for order_position_data in order_positions_data: order_position = OrderProduct( order=order, product=order_position_data['product'], quantity=order_position_data['quantity']) raw_order_positions.append(order_position) OrderProduct.objects.bulk_create(raw_order_positions) return order
def getProductItem(self, item, orderId, pets): response = None if item['type'] == "product": product = Product.objects.get( pk=item['id'] ) orderProduct = OrderProduct( pType = item['type'], product_id = item['id'], order_id = orderId, pet_id = item['pet'], unit_price = product.price, quantity = item['quantity'] ) totalPrice = product.price*item['quantity'] tmpProductPrices = None # Recurring Purchases # if 'is_recurring' in item and item['is_recurring'] == True: product.is_recurring = item['is_recurring'] orderProduct.order_every = item['orderEvery'] if 'orderEvery' in item else '' orderProduct.date = item['scheduleDate'] tmpProductPrices = self.getRecurringProdPrice(item, product)[0] orderProduct.unit_price = tmpProductPrices.price totalPrice = orderProduct.unit_price * item['quantity'] else: product.is_recurring = False totalPrice = orderProduct.unit_price * item['quantity'] response = { 'item': orderProduct, 'source': product, 'pet': next((x for x in pets if x.id == item['pet']), None), 'totalPrice': totalPrice, 'productPrice': tmpProductPrices if tmpProductPrices is not None else None } else: service = Service.objects.get( pk=item['id'] ) orderProduct = OrderProduct( pType = item['type'], service_id = item['id'], order_id = orderId, pet_id = item['pet'], unit_price = service.price, quantity = item['quantity'], timeOption = item['timeOption'], date = item['scheduleDate'], time = item['time'] if 'time' in item else '', notes = item['notes'] if 'notes' in item else '', ) totalPrice = service.price*item['quantity'] # Recurring Purchases if service.is_recurring: orderProduct.order_every = item['orderEvery'] if 'orderEvery' in item else '' orderProduct.scheduleDate = item['scheduleDate'] response = { 'item': orderProduct, 'source': service, 'pet': next((x for x in pets if x.id == item['pet']), None), 'totalPrice': totalPrice } return response
def checkout(request): category = Category.objects.all() current_user = request.user print(current_user) cart = ShopCart.objects.filter(user_id=current_user.id) total = 0 for rs in cart: total += rs.product.price * rs.quantity print(total) grand_total = total + (total * 0.18) form = OrderForm() context = { 'category': category, 'shopcart': cart, 'total': total, 'grand_total': grand_total, 'form': form } if request.method == 'POST': print('post recived') form = OrderForm(request.POST) print(form) if form.is_valid(): print('valid') data = Order() data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.state = form.cleaned_data['state'] data.country = form.cleaned_data['country'] data.zip = form.cleaned_data['zip_code'] data.phone = form.cleaned_data['phone'] data.user_id = current_user.id data.total = total data.ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(7).upper() data.code = ordercode print(ordercode) data.save() shop_cart = ShopCart.objects.filter(user_id=current_user.id) total_cart = 0 for rs in shop_cart: detail = OrderProduct() detail.order_id = data.id detail.product_id = rs.product_id detail.user_id = current_user.id detail.quantity = rs.quantity detail.price = rs.product.price detail.amount = rs.amount total_cart += rs.amount print(detail.amount) detail.save() # reduce quantity of sold product from amount of product product = Product.objects.get(id=rs.product_id) product.amount -= rs.quantity product.save() ShopCart.objects.filter(user_id=current_user.id).delete() request.session['cart_items'] = 0 messages.success( request, "Your Order Has Been Completed Successfully, Thank You!") send_mail_task.delay(ordercode) sleepy.delay(30) print('mail sent') return render(request, 'shop/order_completed.html', { 'ordercode': ordercode, 'category': category }) return render(request, 'shop/checkout.html', context)
def order(request_): category = Category.objects.all() current_user = request_.user print(current_user) cart = ShopCart.objects.filter(user_id=current_user.id) total = 0 for rs in cart: total += rs.product.price * rs.quantity print(total) grand_total = total + (total * 0.18) if request_.method == 'POST': print('post recived') form = OrderForm(request_.POST) print(form) if form.is_valid(): print('valid') data = Order() data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.state = form.cleaned_data['state'] data.country = form.cleaned_data['country'] data.zip = form.cleaned_data['zip_code'] data.phone = form.cleaned_data['phone'] data.user_id = current_user.id data.total = total data.ip = request_.META.get('REMOTE_ADDR') ordercode = get_random_string(7).upper() data.code = ordercode print(ordercode) data.save() shop_cart = ShopCart.objects.filter(user_id=current_user.id) total_cart = 0 for rs in shop_cart: detail = OrderProduct() detail.order_id = data.id detail.product_id = rs.product_id detail.user_id = current_user.id detail.quantity = rs.quantity detail.price = rs.product.price detail.amount = rs.amount total_cart += rs.amount print(detail.amount) detail.save() # reduce quantity of sold product from amount of product product = Product.objects.get(id=rs.product_id) product.amount -= rs.quantity product.save() ShopCart.objects.filter(user_id=current_user.id).delete() request_.session['cart_items'] = 0 messages.success( request_, "Your Order Has Been Completed Successfully, Thank You!") send_mail( 'Your Order Has Been Received!', 'Thanks For Shopping With Us, Your order will be delivered in 5-6 working days! Your Order No. :' + ordercode, '*****@*****.**', ['*****@*****.**'], fail_silently=False) print('mail sent') return render(request_, 'shop/order_completed.html', { 'ordercode': ordercode, 'category': category }) return None
def orderproduct(request): category = Category.objects.all() current_user = request.user userAddress = UserAddress.objects.filter(user_id=current_user.id) shopcart = ShopCart.objects.filter(user_id=current_user.id) ordercode = get_random_string(10).upper() couponInfo = [] from offer.views import checkValidCoupon couponInfo = checkValidCoupon(request) from offer.views import applyWallet applyWalletInfo = applyWallet(request) total = 0 discountlessTotal = 0 discountOff = 0 for rs in shopcart: if rs.product.variant == 'None': try: disP = ProductDiscount.objects.get(product_id=rs.product.id, variant_id=rs.variant_id) actualPrice = rs.product.price nowPrice = actualPrice - actualPrice * disP.discountPercent / 100 print(disP, nowPrice) except: actualPrice = rs.product.price nowPrice = actualPrice total += nowPrice * rs.quantity discountlessTotal += actualPrice * rs.quantity else: try: disP = ProductDiscount.objects.get(product_id=rs.product.id, variant_id=rs.variant_id) actualPrice = rs.variant.price nowPrice = actualPrice - actualPrice * disP.discountPercent / 100 print(disP, nowPrice) except: actualPrice = rs.variant.price nowPrice = actualPrice total += nowPrice * rs.quantity discountlessTotal += rs.variant.price * rs.quantity #check user has subscribed to any plan or not. priceOff is the amount subtract from original price. try: activePlan = Subscriber.objects.filter(user_id=request.user.id, status='Active')[0] s_id = activePlan.subcription_id plan_info = Subscription_Duration.objects.get(id=s_id) limit_amount = plan_info.limit_amount percentage = plan_info.percentage if total * percentage / 100 > limit_amount: totalprice = total - limit_amount priceOff = limit_amount else: totalprice = total - total * percentage / 100 priceOff = total * percentage / 100 except: totalprice = total priceOff = 0 if request.method == 'POST': # if there is a post form = OrderForm(request.POST) # return HttpResponse(request.POST.items()) if form.is_valid(): # Send Credit card to bank, If the bank responds ok, continue, if not, show the error # .............. data = Order() data.first_name = form.cleaned_data[ 'first_name'] # get product quantity from form data.last_name = form.cleaned_data['last_name'] #data.address = form.cleaned_data['address'] #data.city = form.cleaned_data['city'] data.phone = form.cleaned_data['phone'] data.locationAddress = form.cleaned_data['locationAddress'] data.houseNo = form.cleaned_data['houseNo'] data.latitude = form.cleaned_data['latitude'] data.longitude = form.cleaned_data['longitude'] print(form.cleaned_data['useWallet']) data.useWallet = form.cleaned_data['useWallet'] data.user_id = current_user.id data.total = total data.priceOffPlan = total - totalprice data.discountOff = discountlessTotal - total walletMoneyDeducted = 0 if form.cleaned_data['useWallet']: walletMoneyDeducted = applyWalletInfo.cashBackTotal if (totalprice <= walletMoneyDeducted): walletMoneyDeducted = totalprice else: walletMoneyDeducted = applyWalletInfo.cashBackTotal paybleAmount = float(totalprice) - float(walletMoneyDeducted) paybleAmount = round(paybleAmount, 2) data.walletDeduction = walletMoneyDeducted try: print(couponInfo.code) cashBackAdded = total * couponInfo.cashBackPercent / 100 if cashBackAdded >= couponInfo.cashBackLimit: cashBackAdded = couponInfo.cashBackLimit data.cashBackIssued = cashBackAdded data.cashBackCoupon = couponInfo.code except: pass data.ip = request.META.get('REMOTE_ADDR') # random code data.code = ordercode data.save() # for rs in shopcart: detail = OrderProduct() detail.order_id = data.id # Order Id detail.product_id = rs.product_id detail.user_id = current_user.id detail.quantity = rs.quantity if rs.product.variant == 'None': detail.price = rs.product.price productDiscountOff = 0 try: disP = ProductDiscount.objects.get( product_id=rs.product.id, variant_id=rs.variant_id) actualPrice = rs.product.price detail.productDiscountOff = actualPrice * disP.discountPercent / 100 except: #actualPrice = rs.product.price detail.productDiscountOff = 0 else: detail.price = rs.variant.price try: disP = ProductDiscount.objects.get( product_id=rs.product.id, variant_id=rs.variant_id) actualPrice = rs.variant.price detail.productDiscountOff = actualPrice * disP.discountPercent / 100 except: # actualPrice = rs.product.price detail.productDiscountOff = 0 detail.variant_id = rs.variant_id detail.amount = detail.quantity * detail.price detail.save() # ***Reduce quantity of sold product from Amount of Product if rs.product.variant == 'None': product = Product.objects.get(id=rs.product_id) product.amount -= rs.quantity product.save() else: variant = Variants.objects.get(id=rs.variant_id) variant.quantity -= rs.quantity variant.save() #************ <> ***************** name = request.user.get_username() print('username is: ', name) #name='tuhin' param_dict = { 'MID': MID, 'ORDER_ID': str(ordercode), 'TXN_AMOUNT': str(paybleAmount), 'CUST_ID': str( UserProfile.objects.get( user_id=current_user.id).user.email), 'INDUSTRY_TYPE_ID': 'Retail', 'WEBSITE': 'WEBSTAGING', 'CHANNEL_ID': 'WEB', 'CALLBACK_URL': 'http://127.0.0.1:8000/order/handleRequest/' + name, } if (paybleAmount == 0 and totalprice > 0): print('Order Successful') # uid = Order.objects.filter(code = str(response_dict['ORDERID'])) # print (uid.get(pk=1)) order_update = Order.objects.get(code=ordercode, user_id=current_user.id) order_update.status = 'Accepted' order_update.paid = True order_update.clientOTP = random.randint(1111, 9999) # order_update.useWallet = True # order_update.refresh_from_db(fields=['status']) Order.save(self=order_update) from offer.views import walletDeduction walletDeduction(request, ordercode) # print(order_update.status) entryDeliveryManagemant = DeliveryManagement() entryDeliveryManagemant.confirmedOrder_id = order_update.id entryDeliveryManagemant.save() current_user = request.user # Access User Session information ShopCart.objects.filter(user_id=current_user.id).delete() request.session['cart_items'] = 0 # Order.objects.filter(user_id=current_user.id, code= ).delete() messages.success(request, "Your Order has been completed. Thank you ") return HttpResponseRedirect( 'http://127.0.0.1:8000/order/handleRequest/' + name) else: param_dict['CHECKSUMHASH'] = checksum.generate_checksum( param_dict, MERCHANT_KEY) form = OrderForm() profile = UserProfile.objects.get(user_id=current_user.id) context = { 'shopcart': shopcart, 'total': total, 'totalprice': totalprice, 'discountlessTotal': discountlessTotal, 'form': form, 'profile': profile, 'param_dict': param_dict, 'priceOff': priceOff, 'couponInfo': couponInfo, 'applyWalletInfo': applyWalletInfo, 'userAddress': userAddress, } return render(request, 'paytm.html', context) context2 = { 'shopcart': shopcart, 'total': total, 'totalprice': totalprice, 'discountlessTotal': discountlessTotal, 'profile': UserProfile.objects.get(user_id=current_user.id), 'priceOff': priceOff, 'couponInfo': couponInfo, 'applyWalletInfo': applyWalletInfo, 'userAddress': userAddress, } return render(request, 'Order_Form.html', context2)
def orderproduct(request): setting = Setting.objects.get(pk=1) category = Category.objects.all() current_user = request.user shopcart = ShopCart.objects.filter(user_id=current_user.id) total = 0 for rs in shopcart: if rs.product.variant == 'None': total += rs.product.price * rs.quantity else: total += rs.variant.price * rs.quantity if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): # apply credit card infromation from the bank like api process data = Order() data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.email = form.cleaned_data['email'] data.country = form.cleaned_data['country'] data.phone = form.cleaned_data['phone'] data.user_id = current_user.id data.total = total data.ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(5).upper() data.code = ordercode data.save() for rs in shopcart: detail = OrderProduct() detail.order_id = data.id detail.product_id = rs.product_id detail.user_id = current_user.id detail.quantity = rs.quantity if rs.product.variant == 'None': detail.price = rs.product.price else: detail.price = rs.variant.price detail.variant_id = rs.variant_id detail.amount = rs.amount detail.save() if rs.product.variant == 'None': product = Product.objects.get(id=rs.product_id) product.amount -= rs.quantity product.save() else: check = Variants.objects.filter(id=rs.product_id) if len(check) > 0: variant = Variants.objects.get(id=rs.product_id) variant.quantity -= rs.quantity variant.save() ShopCart.objects.filter(user_id=current_user.id).delete() request.session['cart_items'] = 0 messages.success(request, "Your Order has been completed. Thank you") template = render_to_string( 'order_confirmation.html', { 'ordercode': ordercode, 'detail': detail, 'detail.quantity': detail.quantity, 'detail.price': detail.price, 'detail.amount': detail.amount, 'category': category }) send_mail('Order Confirmation', 'Your order has been recieved!', settings.EMAIL_HOST_USER, ['*****@*****.**', data.email], fail_silently=False, html_message=template) return render( request, 'order_completed.html', { 'ordercode': ordercode, 'detail': detail, 'detail.quantity': detail.quantity, 'detail.price': detail.price, 'detail.amount': detail.amount, 'category': category }) else: messages.warning(request, form.errors) return HttpResponseRedirect("/order/orderproduct") form = OrderForm() # profile = UserProfile.objects.get(user_id=current_user.id) setting = Setting.objects.get(pk=1) context = { 'shopcart': shopcart, 'setting': setting, 'total': total, 'form': form, # 'profile': profile, 'category': category, } return render(request, 'order_form.html', context)
def orderproduct(request): category = Category.objects.all() current_user = request.user shopcart = ShopCart.objects.filter(user_id=current_user.id) total = 0 for rs in shopcart: if rs.product.variant == 'None': total += rs.product.price * rs.quantity else: total += rs.variant.price * rs.quantity transport = 0 for rs in shopcart: transport += rs.product.transportation * rs.quantity final_total = total + transport amount = 0 for rs in shopcart: amount += rs.quantity if request.method == 'POST': # if there is a post form = OrderForm(request.POST) # return HttpResponse(request.POST.items()) if form.is_valid(): # Send Credit card to bank, If the bank responds ok, continue, if not, show the error req_data = { "merchant_id": MERCHANT, "amount": amount, "callback_url": CallbackURL, "description": description, "metadata": {"mobile": mobile, "email": email} } req_header = {"accept": "application/json", "content-type": "application/json'"} req = requests.post(url=ZP_API_REQUEST, data=json.dumps( req_data), headers=req_header) authority = req.json()['data']['authority'] if len(req.json()['errors']) == 0: return redirect(ZP_API_STARTPAY.format(authority=authority)) else: e_code = req.json()['errors']['code'] e_message = req.json()['errors']['message'] return HttpResponse(f"Error code: {e_code}, Error Message: {e_message}") # .............. data = Order() data.first_name = form.cleaned_data['first_name'] # get product quantity from form data.last_name = form.cleaned_data['last_name'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.phone = form.cleaned_data['phone'] data.user_id = current_user.id data.total = total data.ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(5).upper() # random cod data.code = ordercode data.save() # for rs in shopcart: detail = OrderProduct() detail.order_id = data.id detail.product_id = rs.product_id detail.user_id = current_user.id detail.quantity = rs.quantity if rs.product.variant == 'None': detail.price = rs.product.price else: detail.price = rs.variant.price detail.variant_id = rs.variant_id detail.amount = rs.amount detail.save() # ***Reduce quantity of sold product from Amount of Product if rs.product.variant == 'None': product = Product.objects.get(id=rs.product_id) product.amount -= rs.quantity product.save() else: variant = Variants.objects.get(id=rs.product_id) variant.quantity -= rs.quantity variant.save() # ************ <> ***************** setting = Setting.objects.get(pk=1) ShopCart.objects.filter(user_id=current_user.id).delete() # Clear & Delete shopcart request.session['cart_items'] = 0 messages.success(request, "خرید شما با موفقیت انجام شد") return render(request, 'Order_Completed.html', {'ordercode': ordercode, 'category': category, 'setting': setting, 'amount':amount}) else: messages.warning(request, form.errors) return HttpResponseRedirect("/order/orderproduct") form = OrderForm() profile = UserProfile.objects.get(user_id=current_user.id) setting = Setting.objects.get(pk=1) context = {'shopcart': shopcart, 'category': category, 'total': total, 'form': form, 'profile': profile, 'transport': transport, 'final_total': final_total, 'setting': setting, 'amount':amount } return render(request, 'Order_Form.html', context)
def siparis(request, id): setting = Setting.objects.get(pk=1) category = Category.objects.all() current_user = request.user # #Access User Session information, şu anki userin bilgilerini aliyor schopcart = ShopCart.objects.get(pk=id) total = schopcart.ay * schopcart.urun.price if id: #shopcartdan id gelmisse data = Order() # order modeline baglaniyor data.user_id = current_user.id #bilgileri Order veritabanina aktariyor data.status = 'New' data.total = total data.ip = request.META.get('REMOTE_ADDR') data.save() #aktarilan verileri kaydediyor schopcart = ShopCart.objects.get( pk=id) #Shopcartdan gelen idli veriyi OrderProducta ekliyor #orderproducta ekleme detail = OrderProduct() #orderproductta baglaniiyor detail.order_id = data.id detail.urun_id = schopcart.urun_id detail.user_id = current_user.id detail.ay = schopcart.ay detail.price = schopcart.urun.price detail.amount = schopcart.amount detail.status = 'New' detail.save() ShopCart.objects.get( pk=id).delete() #shopcartdan alinan veriyi siliyor prodata = Property.objects.get( pk=schopcart.urun_id) #shopcartdan siparis verilen urunu aliyor prodata.status = "False" #statusunu false yapiyor prodata.save() messages.success( request, 'Siparisiniz Basariyla Alinmistir') #basarili islem mesaji context = { 'setting': setting, 'category': category, 'shopcart': schopcart, 'total': total, } return HttpResponseRedirect('/user/orders') #user orderse gonderiyor else: messages.warning(request, "Siparis Alinamadi") #basarisiz islem return HttpResponseRedirect('/user/shopcart') #shopcartda kaliyor
def orderproduct(request): category = Category.objects.all() current_user = request.user shopcart = ShopCart.objects.filter(user_id=current_user.id) # profile = UserProfile.objects.get(user_id=current_user.id) total_quantity = 0 total = 0 for rs in shopcart: total += rs.product.price * rs.quantity total_quantity += rs.quantity # return HttpResponse(str(total)) if request.method == 'POST': # if there is a post form = OrderForm(request.POST) if form.is_valid(): data = Order() data.first_name = form.cleaned_data['first_name'] # get product quantity from form data.last_name = form.cleaned_data['last_name'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.phone = form.cleaned_data['phone'] data.user_id = current_user.id data.total = total data.total_quantity = total_quantity data.ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(10).upper() # random code data.code = ordercode data.save() # Move Shopcart items to Order Product items shopcart = ShopCart.objects.filter(user_id=current_user.id) for rs in shopcart: detail = OrderProduct() detail.order_id = data.id # Order id detail.product_id = rs.product_id detail.user_id = current_user.id detail.quantity = rs.quantity detail.price = rs.product.price detail.amount = rs.amount detail.save() # Reduce quantity of sold product from Amount of Product product = Product.objects.get(id=rs.product_id) product.amount -= rs.quantity product.save() ShopCart.objects.filter(user_id=current_user.id).delete() request.session['cart_items'] = 0 messages.success(request, "Your Order Has Been Completed! Thank you!") return render(request, 'ordercomplete.html', {'ordercode': ordercode, 'category': category}) else: messages.warning(request, form.errors) return HttpResponseRedirect("/order/orderproduct") form = OrderForm shopcart = ShopCart.objects.filter(user_id=current_user.id) profile = UserProfile.objects.get(user_id=current_user.id) context = { 'shopcart': shopcart, 'category': category, 'total': total, 'total_quantity': total_quantity, 'profile': profile, 'form': form, } return render(request, 'orderproduct.html', context)
def orderproduct(request): category = Category.objects.all() current_user = request.user schopcart = Shopcart.objects.filter(user_id=current_user.id) total = 0 for rs in schopcart: total += rs.quantity if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): data = Order() data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.country = form.cleaned_data['country'] data.phone = form.cleaned_data['phone'] data.user_id = current_user.id data.total = total data.ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(5).upper() tarih = datetime.now() + timedelta(days=15) data.teslim_tarih = tarih data.code = ordercode data.save() # Move Shopcart items to order Product items schopcart = Shopcart.objects.filter(user_id=current_user.id) for rs in schopcart: detail = OrderProduct() detail.order_id = data.id #order id detail.product_id = rs.product_id detail.user_id = current_user.id detail.quantity = rs.quantity #reduce quantity of sold product product = Product.objects.get(id=rs.product_id) product.amount -= rs.quantity product.save() #************* <> ********* detail.save() Shopcart.objects.filter( user_id=current_user.id).delete() #clear and delete shop cart request.session['cart_items'] = 0 messages.success(request, "Kitabı Ödünç Aldınız, Teşekkür Ederiz") return render(request, 'Order_Completed.html', { 'ordercode': ordercode, 'category': category, 'tarih': tarih }) else: messages.warning(request, form.errors) return HttpResponseRedirect("/order/orderproduct") form = OrderForm() profile = UserProfile.objects.get(user_id=current_user.id) context = { 'schopcart': schopcart, 'category': category, 'total': total, 'form': form, 'profile': profile } return render(request, 'Order_Form.html', context)
def orderproduct(request): setting = Setting.objects.get(pk=1) category = Category.objects.all() product = Product.objects.all() current_user = request.user shopcart = ShopCart.objects.filter(user_id=current_user.id) total = 0 for rs in shopcart: total += rs.product.price * rs.quantity if request.method == 'POST': # if there is a post form = OrderForm(request.POST) if form.is_valid(): #kredi kartı bilgilerini bankaya gönder onay gelirse dewamkee #<*><*><*><*># data = Order() data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.phone = form.cleaned_data['phone'] data.user_id = current_user.id data.total = total data.ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(8).upper() #random kod üretir data.code = ordercode data.save() #move shopcart items to order products items shopcart = ShopCart.objects.filter(user_id=current_user.id) for rs in shopcart: detail = OrderProduct() detail.order_id = data.id #order id detail.product_id = rs.product_id detail.user_id = current_user.id detail.quantity = rs.quantity detail.price = rs.product.price detail.amount = rs.amount detail.save() #***** reduce quantity of sold product from amount of product product = Product.objects.get(id=rs.product_id) product.amount -= rs.quantity product.save() #****+++---***** ShopCart.objects.filter( user_id=current_user.id).delete() #Clear and Delete ShopCart request.session['cart_items'] = 0 messages.success( request, "Üyeliğiniz başarıyla tamamlanmıştır. Sporla kalın! ") return render(request, 'Order_Completed.html', { 'ordercode': ordercode, 'category': category, 'setting': setting }) else: messages.warning(request, form.errors) return HttpResponseRedirect("/order/orderproduct/") form = OrderForm() profile = UserProfile.objects.get(user_id=current_user.id) context = { 'category': category, 'shopcart': shopcart, 'form': form, 'total': total, 'profile': profile, 'product': product, 'setting': setting, } return render(request, 'Order_Form.html', context)
def orderproduct(request): category = Category.objects.all() current_user = request.user shopcart = ShopCart.objects.filter(user_id=current_user.id) profilepro = ProfilePro.objects.filter(user_id=current_user.id) total = 0 for rs in shopcart: if rs.product.variant == 'None': total += rs.quantity * (rs.product.price-(rs.product.price*(rs.product.remise/100))) else: total += rs.variant.price * rs.quantity if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): # Send Credit card information to bank and get result # If payment accepted continue else send payment error to checkout page data=Order() data.note = form.cleaned_data['note'] data.user_id = current_user.id data.total = total data.ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(5).upper() data.code = ordercode data.save() # Save Shopcart items to Order detail items shopcart = ShopCart.objects.filter(user_id=current_user.id) for rs in shopcart: detail = OrderProduct() detail.order_id = data.id # Order Id detail.compte = profilepro.compte # Order Id detail.product_id = rs.product_id detail.user_id = current_user.id detail.quantity = rs.quantity if rs.product.variant == 'None': detail.price = rs.product.price else: detail.price = rs.variant.price detail.variant_id = rs.variant_id detail.remise = rs.product.remise detail.amount = rs.amount detail.order_amount = data.total detail.note = data.note detail.save() # Reduce product Amount (quantity) if rs.product.variant=='None': product = Product.objects.get(id=rs.product_id) product.amount -= rs.quantity product.save() else: variant = Variants.objects.get(id=rs.product_id) variant.quantity -= rs.quantity variant.save() ShopCart.objects.filter(user_id=current_user.id).delete() # Clear & Delete shopcart request.session['cart_items']=0 messages.success(request, "Your order has been completed. Thank You ") return render(request, 'Order_Completed.html',{'ordercode':ordercode, 'category':category}) else: messages.warning(request, form.errors) return HttpResponseRedirect("/order/orderproduct") form = OrderForm() shopcart = ShopCart.objects.filter(user_id=current_user.id) profile = UserProfile.objects.get(user_id=current_user.id) context = {'shopcart': shopcart, 'category': category, 'total': total, 'form': form, 'profile': profile, 'profilepro': profilepro, } return render(request, 'Order_Form.html', context)
def orderproduct(request): category = Category.objects.all() current_user = request.user shopcart = ShopCart.objects.filter(user_id=current_user.id) total = 0 for rs in shopcart: total += rs.product.fiyat * rs.quantity if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): data = Order() data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.phone = form.cleaned_data['phone'] data.user_id = current_user.id data.total = total data.ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(5).upper() data.code = ordercode data.save() #move shopcrt items for order products items shopcart = ShopCart.objects.filter(user_id=current_user.id) for rs in shopcart: #schopcart detail = OrderProduct() detail.order_id = data.id detail.product_id = rs.product_id detail.user_id = current_user.id detail.quantity = rs.quantity detail.fiyat = rs.product.fiyat detail.stok_durum = rs.stok_durum detail.save() # ***************< Reduce >***************# product = Kitap.objects.get(id=rs.product_id) product.stok_durum -= rs.quantity product.save() #***************<^^^^^^^^^^>***************# ShopCart.objects.filter(user_id=current_user.id).delete() request.session['cart_items'] = 0 messages.success(request, "Your order has been completed , thank you!") return render(request, "Order_Complated.html", { 'ordercode': ordercode, 'category': category }) else: messages.warning(request, form.errors) return HttpResponseRedirect("/order/orderproduct") form = OrderForm() profile = UserProfile.objects.get(user_id=current_user.id) context = { 'shopcart': shopcart, # hoca Schopcart yazmis 'category': category, 'total': total, 'profile': profile, 'form': form, } return render(request, 'Order_Form.html', context)
def orderproductviews(request): category = Category.objects.all() current_user = request.user shopcart = ShopCart.objects.filter(user_id=current_user.id) total = 0 for rs in shopcart: total += rs.product.discount_price * rs.quantity if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): data = Order() data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.phone = form.cleaned_data['phone'] data.region = form.cleaned_data['region'] data.district = form.cleaned_data['district'] data.street_address = form.cleaned_data['street_address'] data.apartment_address = form.cleaned_data['apartment_address'] data.user_id = current_user.id data.total = total data.ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(5).upper() data.code = ordercode data.save() shopcart = ShopCart.objects.filter(user_id=current_user.id) for rs in shopcart: detail = OrderProduct() detail.order_id = data.id detail.product_id = rs.product_id detail.user_id = current_user.id detail.quantity = rs.quantity detail.color = rs.color detail.size = rs.size detail.price = rs.product.price detail.save() ShopCart.objects.filter(user_id=current_user.id).delete() request.session['cart_items'] = 0 messages.success(request, "Your Oder has been completed. Thank you") context = {'category': category, 'ordercode': ordercode } return render(request, 'order_completed.html', context) #return redirect('/order/payment/') else: messages.warning(request, form.errors) return HttpResponseRedirect("/order/orderproduct/") form = OrderForm() profile = UserProfile.objects.get(user_id=current_user.id) context = {'shopcart': shopcart, 'category': category, 'total': total, 'form': form, 'profile': profile } return render(request, 'check-out.html', context)
def orderproduct(request): #form = OrderForm() category = Category.objects.all() setting = Setting.objects.all() current_user = request.user profile = UserProfile.objects.get(User_id=current_user.id) shopcart = ShopCart.objects.filter(User_id=current_user.id) orderqty = ShopCart.objects.filter(User_id=current_user.id).aggregate( Sum('Quantity')) orderqty = orderqty['Quantity__sum'] #print(orderqty) total = 0 for sctotal in shopcart: total += sctotal.Quantity * sctotal.Product.Price #print(total) if request.method == 'POST': form = OrderForm(request.POST) #print(form) #print(request.POST['First_name']) if form.is_valid(): data = Order() data.First_name = form.cleaned_data['First_name'] data.Last_name = form.cleaned_data['Last_name'] data.City = form.cleaned_data['City'] data.Country = form.cleaned_data['Country'] data.Phone = form.cleaned_data['Phone'] data.Address = form.cleaned_data['Address'] data.User_id = current_user.id data.Total = total data.Ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(5).upper() data.Code = ordercode #print(ordercode) data.save() shopcart = ShopCart.objects.filter(User_id=current_user.id) for sc in shopcart: orderdetails = OrderProduct() orderdetails.Order_id = data.id orderdetails.User_id = current_user.id orderdetails.Product_id = sc.Product_id #print(orderdetails.Product_id) orderdetails.Quantity = sc.Quantity orderdetails.Price = sc.Product.Price #orderdetails.Price = sc.price orderdetails.Amount = sc.amount #orderdetails.Amount = sc.Product.Price * sc.Quantity orderdetails.save() #Quantity Deduction From Stock product = Product.objects.get(id=sc.Product_id) product.Amount -= sc.Quantity product.save() shopcart = ShopCart.objects.filter( User_id=current_user.id).delete() request.session['cart_items'] = 0 messages.success(request, 'Your order is completed successfully') context = { 'ordercode': ordercode, 'category': category, 'setting': setting, } return render(request, 'order_complete.html', context) else: #Need to code another system here. This only for test basis print('Form is not valid') else: #Need to code another system here. This only for test basis print('Form is not posted') context = { 'category': category, 'setting': setting, 'shopcart': shopcart, 'orderqty': orderqty, 'total': total, 'profile': profile, } return render(request, 'order_form.html', context)