The problem of the following code is that I want to redirect to cart.html page after the task has been completed. But I am actually stuck couldn’t see any good example that treats a similar scenario like this. Your help will be highly appreciated.
class AddToCartView(TemplateView):
template_name = "carts/addtocart.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# get product id from requested url
product_id = self.kwargs['pro_id']
# get product
product_obj = Meals.objects.get(id=product_id)
# check if cart exists
cart_id = self.request.session.get("cart_id", None)
if cart_id:
cart_obj = Cart.objects.get(id=cart_id)
this_product_in_cart = cart_obj.cartproduct_set.filter(
product=product_obj)
# item already exists in cart
if this_product_in_cart.exists():
cartproduct = this_product_in_cart.last()
cartproduct.quantity += 1
cartproduct.subtotal += product_obj.selling_price
cartproduct.save()
cart_obj.total += product_obj.selling_price
cart_obj.save()
messages.success(self.request, 'Meal successfully added')
# new item is added in cart
else:
cartproduct = CartProduct.objects.create(
cart=cart_obj, product=product_obj, rate=product_obj.selling_price, quantity=1, subtotal=product_obj.selling_price)
cart_obj.total += product_obj.selling_price
cart_obj.save()
messages.success(self.request, 'Meal successfully added')