def cart_add(request, product_id): form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data quantity = cd['quantity'] update_quantity = cd['update'] product = get_object_or_404(Product, id=product_id) cart = get_cart(request) if not cart.id: cart.save() try: cart_item = cart.items.get(product_id=product) except CartItem.DoesNotExist: cart_item = None if cart_item is None: cart_item = CartItem(product_id=product.id, quantity=quantity, cart=cart, price=product.price) elif cart_item.is_deleted: cart_item.quantity = quantity cart_item.is_deleted = False elif update_quantity: cart_item.quantity = quantity else: cart_item.quantity += quantity cart_item.save() return redirect('cart:cart_detail')
def order_create(request): cart = get_cart(request) if cart.is_empty: return redirect('cart:cart_detail') if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save(commit=False) order.user = request.user order.cart = cart if cart.coupon and cart.coupon.is_valid: order.coupon = cart.coupon order.discount = cart.discount order.save() for item in cart.active_items: OrderItem.objects.create(order=order, product=item.product, price=item.price, quantity=item.quantity) cart.is_ordered = True cart.save() messages.success( request, _("Your order has been successfully completed. Your order number is" ) + str(order.id)) return redirect('shop:product_list') else: form = OrderCreateForm return render(request, 'orders/order/create.html', { 'cart': cart, 'form': form })
def coupon_apply(request): form = CouponApplyForm(request.POST) if form.is_valid(): try: cart = get_cart(request) coupon = Coupon.objects.get(code__iexact=form.cleaned_data['code']) if coupon.is_valid: cart.coupon = coupon cart.save() messages.success(request, _('Coupon was applied successfully')) else: messages.error(request, _("Coupon isn't valid")) except Coupon.DoesNotExist: messages.error(request, _("Coupon wasn't found")) return redirect('cart:cart_detail')
def cart_detail(request): return render(request, 'cart/detail.html', { 'cart': get_cart(request), 'coupon_apply_form': CouponApplyForm(), })
def cart_remove(request, product_id): get_cart(request).items.filter(product_id=get_object_or_404(Product, id=product_id).id, is_deleted=False) \ .update(is_deleted=True) return redirect('cart:cart_detail')