def add_item(request): if request.method == 'POST': post_data = json.loads(request.body) service = SessionObjectService('cart') cart = service.get_or_create(request) serializer = CartItemSerializer(data=post_data) if serializer.is_valid(): item = serializer.save() if item in cart: response = { 'text': 'Данный товар уже в корзине.', 'items_number': cart.get_items_number(), 'total_price': cart.get_total_price(), } return JsonResponse(response) cart.add_item(item) service.save(request, session_object=cart) response = { 'text': 'Товар добавлен в корзину.', 'items_number': cart.get_items_number(), 'total_price': cart.get_total_price(), } return JsonResponse(response) else: raise Http404 else: raise Http404()
def post(self, request, *args, **kwargs): form = forms.OrderDeliveryForm(data=request.POST) if form.is_valid(): service = SessionObjectService('order') order = service.get_or_create(request) order.update(form.cleaned_data) service.save(request, order) order['current_form'] = 'payment' return redirect(reverse_lazy('order:payment')) else: context = self.get_context_data(request) context['form'] = form return render(request, 'checkout_delivery.html', context)
def remove_item(request): if request.method == 'POST': post_data = json.loads(request.body) service = SessionObjectService('cart') cart = service.get_or_create(request) cart.remove_item_by_product_id_and_size( post_data.get('id'), post_data.get('size'), ) service.save(request, cart) return JsonResponse({ 'text': 'Товар удален из корзины.', 'items_number': cart.get_items_number(), 'total_price': cart.get_total_price(), }) else: raise Http404()
def change_item_quantity(request): if request.method == 'POST': post_data = json.loads(request.body) service = SessionObjectService('cart') cart = service.get_or_create(request) changed_item = cart.change_item_quantity( post_data.get('id'), post_data.get('size'), int(post_data.get('quantity')), ) service.save(request, cart) context = { 'text': 'Количество изменено.', 'item_total': changed_item.get_total_price(), 'cart_total': cart.get_total_price(), } return JsonResponse(context) else: raise Http404()
def toggle_item(request): if request.method == 'POST': post_data = json.loads(request.body) service = SessionObjectService('favorites') favorites = service.get_or_create(request) product_id = int(post_data.get('id')) if product_id in favorites: item = favorites._get_item_by_product_id(product_id) favorites.remove_item(item) service.save(request, favorites) response = {'text': 'Товар удален из избранного', 'status': 201} else: item = FavoritesItem(product_id=post_data.get('id')) favorites.add_item(item) service.save(request, favorites) response = {'text': 'Товар добавлен в избранное', 'status': 200} return JsonResponse(response) else: raise Http404('Only post allowed')