def new_order(request): from website.forms import NewOrderForm form = NewOrderForm(request.POST or None) if form.is_valid(): staff = request.user.get_profile() order = Order( staff=staff, tourist=form.cleaned_data['tourist'], country=form.cleaned_data['country'], dt_in=form.cleaned_data['dt_in'], oper=form.cleaned_data['oper'], order_value=form.cleaned_data['order_value'], currency=form.cleaned_data['currency'], comment=form.cleaned_data['order_comment']) order.save() pay = Payment( payment_type=form.cleaned_data['pay_type'], order=order, staff=staff, pay=form.cleaned_data['pay'], rate=form.cleaned_data['rate'], comment=form.cleaned_data['pay_comment']) pay.save() messages.add_message(request, messages.SUCCESS, u"Заявка успешно зарегистрирована под номером - %d." % order.id) return redirect('message_list') return render(request, 'new_order.html', {'form': form})
def orderdata(request): Name = request.POST.get('cname') Username = request.POST.get('username') Email = request.POST.get('email') Address = request.POST.get('address') Phonenumber = request.POST.get('PNumber') State = request.POST.get('state') Country = request.POST.get('country') Zip = request.POST.get('zip') Uid = request.session.get('userid') print("***********", Uid) cartob = Cart.objects.filter(Userid=Uid, Status=0) print("//////////////////", cartob) for a in cartob: obj = Order(Cartid=Cart.objects.get(id=a.id), Order_Name=Name, Order_Uname=Username, Order_Email=Email, Order_Address=Address, Order_Phone=Phonenumber, Order_State=State, Order_Country=Country, Order_Zip=Zip) print("############", obj) obj.save() Cart.objects.filter(id=a.id).update(Status=1) return redirect(home)
def product_detail(request, product): """function to make the view for a product detail Arguments: request {http} -- the request that triggered the function product {string} -- passed into the function from the url, expected to be the id of the product we are looking for Returns: render -- function either renders the product detail html page, or an error page if the product was not found """ # try to get product object try: current_product = Product.objects.get(pk=product) except ObjectDoesNotExist: return render(request, 'website/404.html', {}) if request.method == "GET": # define template name for get requests template_name = 'website/product_detail.html' # get how many of this product is remaining product_remaining = current_product.quantity - len([ product for order in Order.objects.all() for product in order.products.all() if product.id == current_product.id ]) # finally render product template return render(request, template_name, { 'product': current_product, 'remaining': product_remaining }) elif request.method == "POST": # get users orders current_user = request.user users_orders = current_user.order_set.all() # try to find one that has not yet been closed open_order = next( (order for order in users_orders if order.date_closed == None), None) # add the product to that order if open_order != None: open_order.products.add(current_product) # if the user has no open orders create one else: new_order = Order( user=current_user, payment_type=None, date_created=datetime.datetime.now(), date_closed=None, ) new_order.save() # add product to that order new_order.products.add(current_product) return render(request, 'website/product_add_sucsess.html', {'product': current_product})
def place_order(self): if self.validate_data(): order = Order() order.advert = self.advert order.advert.set_reserved() order.set_status_created() order.set_delivery(self.delivery_type, self.address) order.contact_info = self.ci order.save() return order
def cart(request): user_id = request.user.id order = Order.objects.raw( '''SELECT * from website_order o WHERE o.customerOrder_id = %s AND o.paymentOrder_id = 1 AND o.deleted = 0''', [user_id]) count = len(order) if count > 0: order = order[0].id all_product_orders = ProductOrder.objects.raw( '''SELECT * from website_productorder po WHERE po.order_id = %s AND po.deleted = 0''', [order]) all_products = [] total = 0 count = 0 for product in all_product_orders: item = Product.objects.raw( '''SELECT * from website_product p WHERE p.id = %s''', [product.product_id]) item = item[0] total += item.price count += 1 item.order_id = product.id all_products.append(item) tax = Decimal(.0945) tax = round(total * tax, 2) total_with_tax = total + tax if count == 0: empty = "Your Bangazon Cart Is Empty" else: empty = "Your Bangazon Cart" context = { "products_in_cart": all_products, "total": total, "count": count, "tax": tax, "total_with_tax": total_with_tax, "empty": empty } return render(request, 'cart.html', context) else: cart = Order(deleted=0, customerOrder_id=user_id, paymentOrder_id=1) cart.save() return HttpResponseRedirect(reverse('website:cart'))
def add_to_cart(request, product_id): user_id = request.user.id order = Order.objects.raw( '''SELECT * from website_order o WHERE o.customerOrder_id = %s AND o.paymentOrder_id = 1 AND o.deleted = 0''', [user_id]) count = len(order) print("count", count) if count == 0: cart = Order(deleted=0, customerOrder_id=user_id, paymentOrder_id=1) cart.save() order = Order.objects.raw( '''SELECT * from website_order o WHERE o.customerOrder_id = %s AND o.paymentOrder_id = 1 AND o.deleted = 0''', [user_id]) order = order[0].id product = ProductOrder(deleted=0, order_id=order, product_id=product_id) product.save() return HttpResponseRedirect(reverse('website:cart'))
def checkout(request): from website.models import Product, Order nonce = request.POST["payment_method_nonce"] #calculate price from session info sessionList = request.session['cartIDs'] totalPrice = 0 for prodID in sessionList: itemRet = Product.objects.values( "product_price", "product_sale_price", "product_sale_true" ).filter( product_id__exact=prodID ) if itemRet[0]["product_sale_true"] == True: totalPrice += float(itemRet[0]["product_sale_price"]) else: totalPrice += float(itemRet[0]["product_price"]) price = totalPrice # Reconfigure braintree.Configuration.configure(braintree.Environment.Sandbox, merchant_id="g5s47h9778vgy9nc", public_key="swxxjv9btyvjh693", private_key="ebabbd95e37f9d60a480bec05ec8aff6") result = braintree.Transaction.sale({ "amount": str(price), "payment_method_nonce": nonce }) if result.is_success == True: # Add to Order object # Create Order Json orderJson = "" sessionList = request.session['cartIDs'] for prodID in sessionList: itemRet = Product.objects.values( "product_id", "product_name", "product_price", "product_sale_price", "product_sale_true" ).filter( product_id__exact=prodID ) orderJson += (str(itemRet[0]["product_id"]) + " ") orderJson += (str(itemRet[0]["product_name"]) + " ") if itemRet[0]["product_sale_true"] == True: orderJson += (str(itemRet[0]["product_sale_price"]) + ",") else: orderJson += (str(itemRet[0]["product_price"]) + ",") # Get ip x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(",")[0] else: ip = request.META.get('REMOTE_ADDR') # Create Order Object order = Order( order_customer_id = int(request.session["userID"]), order_product_id_quantity_json = orderJson, order_ip = ip, order_last_4_credit = 0000 ) order.save() # Session setting request.session['cartIDs'] = [] request.session['paymentError'] = 0 return HttpResponseRedirect('/store/') else: request.session['paymentError'] = 1 return HttpResponseRedirect('/store/checkout/')
def order(request, order): try: my_good = [] context = {} count = {} summ = 0 if not request.user.is_authenticated(): for p in request.session.keys(): if p.isdigit(): d = int(p) my_good.append(Goods.objects.get(id=d)) count[d] = request.session[p].replace( auth.get_user(request).username, '') summ += int(count[d]) * int(Goods.objects.get(id=d).price) context['mas'] = my_good else: good = Basket.objects.filter(user_id=request.user.id) context['mas'] = good for p in good: summ += int(p.goods_id.price) * int(p.num_items) context['city_list'] = City.objects.all() context['count'] = count context['summ'] = summ context['first_cat'] = first_cat = Category.objects.exclude( name__icontains='.') context['phone_error'] = False context['adress_error'] = False context['type'] = order if request.POST: try: adress = request.POST['adress'] except MultiValueDictKeyError: adress = 0 telephone = str(request.POST['telephone']).encode('utf-8') use_name = request.POST['use_name'] town = request.POST['town'] if re.search('^\d-\d\d\d-\d\d\d-\d\d-\d\d$', telephone) is None: context['phone_error'] = 'введите правильный номер!' if order == "home": if (len(adress) == 0): context['adress_error'] = "введите адрес" if (context['phone_error'] != False) or (context['adress_error'] != False): return render(request, 'order.html', context) else: num = random.randint(1000000, 99999999) while Order.objects.filter(num_order=num): num = random.randint(1000000, 99999999) if not request.user.is_authenticated(): for p in request.session.keys(): if p.isdigit(): d = int(p) b = Order(num_order=num, goods_id=Goods.objects.get(id=d), city_id=City.objects.get(name=town), num_items=request.session[p], use_name=use_name, telephones=telephone, adress=adress) b.save() del request.session[p] context['ok'] = "Ваш заказ принят" return render(request, 'register.html', context) else: basket = Basket.objects.filter(user_id=request.user.id) for p in basket: b = Order(num_order=num, goods_id=Goods.objects.get(id=p.id), city_id=City.objects.get(name=town), num_items=p.num_items, use_name=use_name, telephones=telephone, adress=adress, user_id=request.user) b.save() Basket.delete(p) return redirect('/auth/buy') return render(request, 'order.html', context) except: raise Http404
def product_details(request, product_id): """ purpose: Allows user to view product_detail view, which contains a very specific view for a singular product if the user clicks "add to order". Their current open order will be updated and the user will be routed to that order. For an example, visit /product_details/1/ to see a view on the first product created displaying title, description, quantity, price/unit, and "Add to order" button author: Taylor Perkins, Justin Short args: product_id: (integer): id of product we are viewing returns: (render): a view of of the request, template to use, and product obj """ # If trying to view, render product corresponding to id passed product = get_object_or_404(Product, pk=product_id) if request.method == "GET": template_name = 'product/details.html' try: if request.user.is_authenticated(): product_liked = LikeDislike.objects.get(product=product, user=request.user) else: product_liked = None except ObjectDoesNotExist: product_liked = None # if trying to to buy, get the user's orders elif request.method == "POST": def create_like_dislike_instance(bool): liked_instance = LikeDislike( user=request.user, product=Product.objects.get(pk=product_id), liked=bool) liked_instance.save() return liked_instance print(request.user.is_authenticated()) try: product_liked = LikeDislike.objects.get(product=product, user=request.user) if product_liked: return HttpResponseRedirect( '/product_details/{}'.format(product_id)) except MultipleObjectsReturned: return HttpResponseRedirect( '/product_details/{}'.format(product_id)) except ObjectDoesNotExist: pass if 'like_dislike' in request.POST: print(request.POST.get('like_dislike')) if request.POST.get('like_dislike') == 'Like': create_like_dislike_instance(True) return HttpResponseRedirect( '/product_details/{}'.format(product_id)) elif request.POST.get('like_dislike') == 'Dislike': create_like_dislike_instance(False) return HttpResponseRedirect( '/product_details/{}'.format(product_id)) elif 'add_to_order' in request.POST: product = get_object_or_404(Product, pk=product_id) template_name = 'product/details.html' all_orders = Order.objects.filter(buyer=request.user) # try to get user's open order. assign the product to an order # we should look into the get_or_create method as a potential refactor try: open_order = all_orders.get(date_complete__isnull=True) user_order = UserOrder(product=product, order=open_order) user_order.save() return HttpResponseRedirect('/view_order') # if no open order, create one. and assign product to it. except ObjectDoesNotExist: open_order = Order(buyer=request.user, payment_type=None, date_complete=None) open_order.save() user_order = UserOrder(product=product, order=open_order) user_order.save() users_orders = Order.objects.filter(buyer=request.user) print(users_orders) return HttpResponseRedirect('/view_order') return render(request, template_name, { "product": product, "product_liked": product_liked })