def basket_add(request, product_id): product = get_object_or_404(Product, pk=product_id) baskets = Basket.objects.filter(user=request.user, product=product) if not baskets.exists(): basket = Basket(user=request.user, product=product) else: basket = baskets.first() basket.quantity += 1 basket.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def add_product(request, **kwargs): pk = kwargs.get('pk') prod = Product.objects.get(pk=pk) old_basket = Basket.objects.filter(product=prod, user=request.user) if old_basket: old_basket[0].quantity += 1 old_basket[0].save() else: new_basket = Basket(product=prod, user=request.user) new_basket.quantity += 1 new_basket.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def basket_add(request, product_id): product = Product.objects.get(id=product_id) baskets = Basket.objects.filter(user=request.user, product=product) if not baskets.exists(): basket = Basket(user=request.user, product=product) basket.quantity += 1 else: basket = baskets.first() basket.quantity += F("quantity") + 1 basket.save() update_queries = list(filter(lambda x: 'UPDATE' in x['sql'], connection.queries)) print(f'query basket_add: {update_queries}') return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def save(self): print(self.data) userIdtemp = self.data['userId'] productIdtemp = self.data['productId'] quantitytemp = self.data['quantity'] pricetemp = self.data['price'] basket = Basket( userId=userIdtemp, productId=productIdtemp, quantity=quantitytemp, price=pricetemp, ) basket.save() return basket
def basket_add(request, pk): if 'login' in request.META.get('HTTP_REFERER'): return HttpResponseRedirect(reverse('mainapp:product', args=[pk])) product = get_object_or_404(Product, pk=pk) basket = Basket.objects.filter(user=request.user, product=product).first() # если корзины у пользователя еще нет # создаем корзину и добавляем туда product if not basket: basket = Basket(user=request.user, product=product) basket.quantity += 1 basket.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def basket_add(request, pk): if 'login' in request.META.get('HTTP_REFERER'): return HttpResponseRedirect(reverse('catalogue:good', args=[pk])) # получить продукт product = get_object_or_404(Product, pk=pk) # получить пользователя request.user # получить такие же продукты у этого пользователя old_basket_item = Basket.objects.filter(user=request.user, product=product) if old_basket_item: old_basket_item[0].quantity += 1 old_basket_item[0].save() else: new_basket_item = Basket(user=request.user, product=product) new_basket_item.quantity += 1 new_basket_item.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def get_basket(self, request): if request._basket_cache is not None: return request._basket_cache num_baskets_merged = 0 manager = Basket.open cookie_key = self.get_cookie_key(request) cookie_basket = self.get_cookie_basket(cookie_key, request, manager) if hasattr(request, 'user') and request.user.is_authenticated: try: basket, __ = manager.get_or_create(owner=request.user) except Basket.MultipleObjectsReturned: old_baskets = list(manager.filter(owner=request.user)) basket = old_baskets[0] for other_basket in old_baskets[1:]: self.merge_baskets(basket, other_basket) num_baskets_merged += 1 basket.owner = request.user if cookie_basket: self.merge_baskets(basket, cookie_basket) num_baskets_merged += 1 request.cookies_to_delete.append(cookie_key) elif cookie_basket: # print("Anonymous user with a basket tied to the cookie") basket = cookie_basket else: # print("return basket empty") basket = Basket() request._basket_cache = basket if num_baskets_merged > 0: pass return basket
def get_context_data(self, **kwargs): data = super(OrderItemsCreate, self).get_context_data(**kwargs) OrderFormSet = inlineformset_factory(Order, OrderItem, form=OrderItemForm, extra=1) if self.request.POST: formset = OrderFormSet(self.request.POST) else: basket_items = Basket.get_items(self.request.user) if len(basket_items): OrderFormSet = inlineformset_factory(Order, OrderItem, form=OrderItemForm, extra=len(basket_items)) formset = OrderFormSet() for num, form in enumerate(formset.forms): form.initial['product'] = basket_items[num].product form.initial['quantity'] = basket_items[num].quantity form.initial['price'] = basket_items[num].product.price # basket_items.delete() else: formset = OrderFormSet() # formset = OrderFormSet() data['orderitems'] = formset return data
def test_basket_item_deleted_when_basket_deleted(self): user = get_user_model().objects.create_user(username='******', email='*****@*****.**', password='******') basket = Basket(owner = user) basket.save() colour = Colour(hex_value = '#ffffff', name = "white", season = "summer") colour.save() category = Category(name = "test_category", display_name = "Test Category") category.save() brand = Brand(name = "test_brand", display_name = "Test Brand") brand.save() product = Product(brand = brand, name = "test name", price = 5.00, image_link = 'www.test.com', description = "test desc") product.save() product.category.add(category) product.product_colors.add(colour) item = BasketItem(basket = basket, product = product, quantity = 1, colour = colour) item.save() basket.delete() self.assertFalse(BasketItem.objects.filter(basket = basket).exists())
def add_to_basket(request): postdata = request.POST.copy() #GET PRODUCT SLUG FROM POST DATA , RETURN BLANK IF EMPTY song_id = postdata.get('song_id','') #GET QUANTITY ADDED, RETURN 1 IF EMPTY #FETCH THE PRODUCT OR RETURN A MISSING PAGE ERROR quantity = postdata.get("qauntity",1) music = get_object_or_404(Music, pk=int(song_id)) #GET PRODUCTS IN CART_ID_SESSION_KEY basket_music = get_basket_items(request) music_in_basket = False #CHECK TO SEE IF ITEM IS ALREADY IN CART_ID_SESSION_KEY for basket_item in basket_music: if basket_item.song.pk == music.id: music_in_basket=True if not music_in_basket: basket = Basket() basket.song = music basket.quantity = quantity basket.basket_id = _basket_id(request) basket.save()
def get_basket(self, key): try: return Basket.objects.get(key=key) except Basket.DoesNotExist: return Basket(key=key)
def basket(request): """ A view to show the current basket """ """ check for a basket cookie """ context_items = basket_context(request) cookie = context_items['cookie'] """ set all the variables to blank """ category = "" selected = "" options = "" baskets = "" servings = "" """ fetch the datasets from the models """ categories = Category.objects.all() products = Product.objects.all() options = Options.objects.all() """ check for a servings variable from the form """ if request.POST: if 'servings' in request.POST: servings = request.POST["servings"] if not re.match("^[0-9]+$", servings): messages.success( request, mark_safe('There was a problem! \ <br> Please reselect a product and try again.')) return redirect(reverse('home')) if request.GET: """ check for a product_add variable from the template """ if 'product_add' in request.GET: product_add = request.GET['product_add'] """ split the product_add variable into its components """ product_add_list = product_add.split(',') category = product_add_list[0] product = product_add_list[1] selected = product_add_list[2] productid = product_add_list[3] """ filter the datasets on the variables from product_add """ options = options.filter(category__in=categories) # Credit: http://morozov.ca/ # tip-how-to-get-a-single-objects-value-with-django-orm.html """ price = products.get(id_no=productid).price """ check for existing basket(s) with the current cookie value """ try: existing_basket = Basket.objects.get(cookie=cookie, category=category, name=product, option=selected) existing_servings = existing_basket.servings """ add the new servings variable to the existing """ updated_servings = existing_servings + int(servings) total_price = float(price) * float(updated_servings) """ save the updated basket and delete the existing """ updated_basket = Basket(cookie=cookie, category=category, name=product, servings=updated_servings, option=selected, total_price=total_price) updated_basket.save() messages.success(request, 'item quantity increased!') existing_basket.delete() except ObjectDoesNotExist: # Credit: https://stackoverflow.com/questions/ # 12572741/get-single-record-from-database-django """ if there is no existing basket, create a new one """ total_price = float(price) * float(servings) basket = Basket(cookie=cookie, category=category, name=product, servings=servings, option=selected, total_price=total_price) basket.save() messages.success(request, 'item added to basket!') baskets = Basket.objects.filter(cookie=cookie) baskets = baskets.order_by('-pk') """ check for a product_edit variable from the template """ if 'product_edit' in request.GET: product_edit = request.GET['product_edit'] """ split the product_add variable into its components """ product_edit_list = product_edit.split(',') updated_selected = product_edit_list[2] item_number = product_edit_list[3] productid = product_edit_list[4] """ check for existing basket(s) with the current cookie value """ try: existing_basket = Basket.objects.get(pk=item_number) product = existing_basket.name category = existing_basket.category price = products.get(id_no=productid).price if servings == "": servings = existing_basket.servings total_price = total_price = float(price) * float(servings) else: total_price = total_price = float(price) * float(servings) """ filter the datasets on the variables from product_add """ options = options.filter(category__in=categories) # Credit: http://morozov.ca/ # tip-how-to-get-a-single-objects-value-with-django-orm.html """ save the updated basket and delete the existing """ updated_basket = Basket(cookie=cookie, category=category, name=product, servings=servings, option=updated_selected, total_price=total_price) updated_basket.save() messages.success(request, 'basket updated!') existing_basket.delete() except ObjectDoesNotExist: # Credit: https://stackoverflow.com/questions/ # 12572741/get-single-record-from-database-django return redirect(reverse('basket_success', args=[cookie])) basket_key = cookie return redirect(reverse('basket_success', args=[basket_key]))
def bartholemew_basket(request): """ A view to let bartholemew work his magic! """ """ check for a basket cookie """ context_items = basket_context(request) cookie = context_items['cookie'] option = 1 menu = Category.objects.all().order_by('id_no') if request.POST: bartholemew_event_type = request.POST['bartholemew_eventType'] bartholemew_min_guests = int( float(request.POST['bartholemew_minGuests'])) bartholemew_max_guests = int( float(request.POST['bartholemew_maxGuests'])) bartholemew_vegan_guests = int( float(request.POST['bartholemew_veganGuests'])) bartholemew_veggie_guests = int( float(request.POST['bartholemew_veggieGuests'])) bartholemew_pesc_guests = int( float(request.POST['bartholemew_pescGuests'])) bartholemew_hotProportion = request.POST['bartholemew_hotProportion'] bartholemew_allergyProportion = ( request.POST['bartholemew_allergyProportion']) """ Calculate the average number of guests """ if bartholemew_max_guests == "": bartholemew_ave_guests = bartholemew_min_guests else: bartholemew_ave_guests = int( (bartholemew_min_guests + bartholemew_max_guests) / 2) bartholemew_nonspec_guests = int(bartholemew_ave_guests - bartholemew_vegan_guests - bartholemew_veggie_guests - bartholemew_pesc_guests) """ Calculate the number of non-allergy meals """ if bartholemew_allergyProportion == "normal": bartholemew_allergyNumber = int(bartholemew_nonspec_guests * 0.2) elif bartholemew_allergyProportion == "medium": bartholemew_allergyNumber = int(bartholemew_nonspec_guests * 0.3) elif bartholemew_allergyProportion == "high": bartholemew_allergyNumber = int(bartholemew_nonspec_guests * 0.4) """ Calculate the number of hot meals """ if bartholemew_hotProportion == "No": bartholemew_hotNumber = int(bartholemew_nonspec_guests * 0.2) elif bartholemew_hotProportion == "Medium amount of": bartholemew_hotNumber = int(bartholemew_nonspec_guests * 0.3) elif bartholemew_hotProportion == "Lots of": bartholemew_hotNumber = int(bartholemew_nonspec_guests * 0.4) """ Calculate the total of specified meals """ bartholemew_specified = int(bartholemew_vegan_guests + bartholemew_veggie_guests + bartholemew_pesc_guests + bartholemew_allergyNumber + bartholemew_hotNumber) bartholemew_unspecified = int(bartholemew_ave_guests - bartholemew_specified) # Credit: https://stackoverflow.com/questions/32389519/ # django-get-10-random-instances-from-a-queryset-and- # order-them-into-a-new-querys """ MAIN COURSES """ """ Generate 3 random main courses for each unspecified guest """ products_main = [ i.id for i in Product.objects.filter(category__course="main") ] products_main_unspecified = [] for i in range(bartholemew_unspecified): random.shuffle(products_main) products_main_shuffled = ([ Product.objects.get(id=i) for i in products_main ]) products_main_unspecified = (products_main_unspecified + products_main_shuffled[0:3]) """ Generate 3 random main courses for each vegan guest """ products_main = ([ i.id for i in Product.objects.filter(category__course="main", allergies__contains="v") ]) products_main_vegan = [] for i in range(bartholemew_vegan_guests): random.shuffle(products_main) products_main_shuffled = ([ Product.objects.get(id=i) for i in products_main ]) products_main_vegan = (products_main_vegan + products_main_shuffled[0:3]) """ Generate 3 random main courses for each vegetarian guest """ products_main = ([ i.id for i in Product.objects.filter(category__course="main", allergies__contains="g") ]) products_main_veggie = [] for i in range(bartholemew_veggie_guests): random.shuffle(products_main) products_main_shuffled = ([ Product.objects.get(id=i) for i in products_main ]) products_main_veggie = (products_main_veggie + products_main_shuffled[0:3]) """ Generate 3 random main courses for each pescatarian guest """ products_main = ([ i.id for i in Product.objects.filter(category__course="main", allergies__contains="p") ]) products_main_pesc = [] for i in range(bartholemew_pesc_guests): random.shuffle(products_main) products_main_shuffled = ([ Product.objects.get(id=i) for i in products_main ]) products_main_pesc = (products_main_pesc + products_main_shuffled[0:3]) """ Generate 3 random main courses for hot food proportion """ products_main = ([ i.id for i in Product.objects.filter(category__course="main", allergies__contains="h") ]) products_hot_food = [] for i in range(bartholemew_hotNumber): random.shuffle(products_main) products_main_shuffled = ([ Product.objects.get(id=i) for i in products_main ]) products_hot_food = (products_hot_food + products_main_shuffled[0:3]) """ SIDE COURSES """ """ Generate 2 random side courses for each unspecified guest """ products_side = ([ i.id for i in Product.objects.filter(category__course="side") ]) products_side_unspecified = [] for i in range(bartholemew_unspecified): random.shuffle(products_side) products_side_shuffled = ([ Product.objects.get(id=i) for i in products_side ]) products_side_unspecified = (products_side_unspecified + products_side_shuffled[0:2]) """ Generate 2 random side courses for each vegan guest """ products_side = ([ i.id for i in Product.objects.filter(category__course="side", allergies__contains="v") ]) products_side_vegan = [] for i in range(bartholemew_vegan_guests): random.shuffle(products_side) products_side_shuffled = ([ Product.objects.get(id=i) for i in products_side ]) products_side_vegan = (products_side_vegan + products_side_shuffled[0:2]) """ Generate 2 random side courses for each vegetarian guest """ products_side = ([ i.id for i in Product.objects.filter(category__course="side", allergies__contains="g") ]) products_side_veggie = [] for i in range(bartholemew_veggie_guests): random.shuffle(products_side) products_side_shuffled = ([ Product.objects.get(id=i) for i in products_side ]) products_side_veggie = (products_side_veggie + products_side_shuffled[0:2]) """ Generate 2 random side courses for each pescatarian guest """ products_side = ([ i.id for i in Product.objects.filter(category__course="side", allergies__contains="p") ]) products_side_pesc = [] for i in range(bartholemew_pesc_guests): random.shuffle(products_side) products_side_shuffled = ([ Product.objects.get(id=i) for i in products_side ]) products_side_pesc = (products_side_pesc + products_side_shuffled[0:2]) """ DESSERT COURSES """ """ Generate 1 random dessert courses for each unspecified guest """ products_dessert = ([ i.id for i in Product.objects.filter(category__course="dessert") ]) products_dessert_unspecified = [] for i in range(bartholemew_unspecified): random.shuffle(products_dessert) products_dessert_shuffled = ([ Product.objects.get(id=i) for i in products_dessert ]) products_dessert_unspecified = (products_dessert_unspecified + products_dessert_shuffled[0:1]) """ Generate 1 random dessert courses for each vegan guest """ products_dessert = ([ i.id for i in Product.objects.filter(category__course="dessert", allergies__contains="v") ]) products_dessert_vegan = [] for i in range(bartholemew_vegan_guests): random.shuffle(products_dessert) products_dessert_shuffled = ([ Product.objects.get(id=i) for i in products_dessert ]) products_dessert_vegan = (products_dessert_vegan + products_dessert_shuffled[0:1]) """ Generate 1 random dessert courses for each vegetarian guest """ products_dessert = ([ i.id for i in Product.objects.filter(category__course="dessert", allergies__contains="g") ]) products_dessert_veggie = [] for i in range(bartholemew_veggie_guests): random.shuffle(products_dessert) products_dessert_shuffled = ([ Product.objects.get(id=i) for i in products_dessert ]) products_dessert_veggie = (products_dessert_veggie + products_dessert_shuffled[0:1]) """ Generate 1 random dessert courses for each pescatarian guest """ products_dessert = ([ i.id for i in Product.objects.filter(category__course="dessert", allergies__contains="p") ]) products_dessert_pesc = [] for i in range(bartholemew_pesc_guests): random.shuffle(products_dessert) products_dessert_shuffled = ([ Product.objects.get(id=i) for i in products_dessert ]) products_dessert_pesc = (products_dessert_pesc + products_dessert_shuffled[0:1]) products_list_main = (products_main_unspecified + products_main_vegan + products_main_veggie + products_main_pesc + products_hot_food) products_list_side = (products_side_unspecified + products_side_vegan + products_side_veggie + products_side_pesc) products_list_dessert = (products_dessert_unspecified + products_dessert_vegan + products_dessert_veggie + products_dessert_pesc) total_cost = 0 for product in products_list_dessert: category = product.category name = product.name price = product.price servings = 1 """ Randomise the available option """ try: category_option = Options.objects.get(category=category) rnd = random.randint(1, 3) if rnd == 1: option = "selected-one" elif rnd == 2: option = "selected-two" elif rnd == 3: option = "selected-three" except ObjectDoesNotExist: option = "none" """ check for existing basket(s) with the current cookie value """ try: existing_basket = Basket.objects.get(cookie=cookie, category=category, name=product, option=option) existing_servings = existing_basket.servings """ add the new servings variable to the existing """ updated_servings = existing_servings + int(servings) price_per_person = float(price) * float(servings) total_price = float(price) * float(updated_servings) """ save the updated basket and delete the existing """ updated_basket = Basket(cookie=cookie, category=category, name=name, servings=updated_servings, option=option, total_price=total_price) updated_basket.save() existing_basket.delete() except ObjectDoesNotExist: """ if there is no existing basket, create a new one """ total_price = float(price) * float(servings) price_per_person = total_price basket = Basket(cookie=cookie, category=category, name=name, servings=servings, option=option, total_price=total_price) basket.save() total_cost = total_cost + price_per_person for product in products_list_side: category = product.category name = product.name price = product.price servings = 1 """ Randomise the available option """ try: category_option = Options.objects.get(category=category) rnd = random.randint(1, 3) if rnd == 1: option = "selected-one" elif rnd == 2: option = "selected-two" elif rnd == 3: option = "selected-three" except ObjectDoesNotExist: option = "none" """ check for existing basket(s) with the current cookie value """ try: existing_basket = Basket.objects.get(cookie=cookie, category=category, name=product, option=option) existing_servings = existing_basket.servings """ add the new servings variable to the existing """ updated_servings = existing_servings + int(servings) price_per_person = float(price) * float(servings) total_price = float(price) * float(updated_servings) """ save the updated basket and delete the existing """ updated_basket = Basket(cookie=cookie, category=category, name=name, servings=updated_servings, option=option, total_price=total_price) updated_basket.save() existing_basket.delete() except ObjectDoesNotExist: """ if there is no existing basket, create a new one """ total_price = float(price) * float(servings) price_per_person = total_price basket = Basket(cookie=cookie, category=category, name=name, servings=servings, option=option, total_price=total_price) basket.save() total_cost = total_cost + price_per_person for product in products_list_main: category = product.category name = product.name price = product.price servings = 1 """ Randomise the available option """ try: category_option = Options.objects.get(category=category) rnd = random.randint(1, 3) if rnd == 1: option = "selected-one" elif rnd == 2: option = "selected-two" elif rnd == 3: option = "selected-three" except ObjectDoesNotExist: option = "none" """ check for existing basket(s) with the current cookie value """ try: existing_basket = Basket.objects.get(cookie=cookie, category=category, name=product, option=option) existing_servings = existing_basket.servings """ add the new servings variable to the existing """ updated_servings = existing_servings + int(servings) price_per_person = float(price) * float(servings) total_price = float(price) * float(updated_servings) """ save the updated basket and delete the existing """ updated_basket = Basket(cookie=cookie, category=category, name=name, servings=updated_servings, option=option, total_price=total_price) updated_basket.save() existing_basket.delete() except ObjectDoesNotExist: """ if there is no existing basket, create a new one """ total_price = float(price) * float(servings) price_per_person = total_price basket = Basket(cookie=cookie, category=category, name=name, servings=servings, option=option, total_price=total_price) basket.save() total_cost = total_cost + price_per_person average_cost = total_cost / bartholemew_ave_guests # https://stackoverflow.com/questions/1995615/ # how-can-i-format-a-decimal-to-always-show-2-decimal-places context = { 'bartholemew_event_type': bartholemew_event_type, 'products_list_main': products_list_main, 'products_list_side': products_list_side, 'products_list_dessert': products_list_dessert, 'total_cost': f'{total_cost:.2f}', 'average_cost': f'{average_cost:.2f}', 'menu': menu, } return render(request, 'bartholemew/bartholemew_output.html', context)