How to use HttpResponseRedirect in Django class based template

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')

My first thought with questions like this is to take a step back and look at the flow of events from a broader perspective.

You show a view -
How does this view get invoked? (What action has the user performed that would cause this view to execute? Was it something done in a previous view? If so, what does that view look like?)

What does the target view look like? (What is the view that you think you need to redirect to.)

Is it a case that you might end up going to different views depending upon what happens in this view?

If this view is a case where a button is pushed to trigger this action, then my first reaction is to believe you’ve chosen the wrong base class for your view. You may want to build this view on the FormView class, which has a success_url attribute that you can use to specify the url to redirect to on a successful submission.
This wouldn’t be an instance of a TemplateView class, because you’re not looking to render a template here - you want to redirect the individual to a different view to possibly render a template from that view.

1 Like