Omar Gonzales
Omar Gonzales

Reputation: 4008

Django: delete cookie from request

I know how to delete a cookie from response:

response = HttpResponseRedirect(self.get_success_url())
response.delete_cookie("item_id")
return response

But how to delete a cookie from request?

I've a view that only has a request but not a response:

I'd like to delete the cart_id cookie when user arrives at my 'thanks.html' page.

def thanks(request):
    order_number = Order.objects.latest('id').id
    return render(request, 'thanks.html', dict(order_number=order_number))

Upvotes: 2

Views: 4063

Answers (1)

Anonymous
Anonymous

Reputation: 12090

You can't delete cookie from a request, or rather it would be an exercise in futility. The way you "delete" (and set) a cookie from the server side is by issuing a specific header on the response. The request only contains headers sent by the client.

All views have a response, it's just not super clear here because there's nothing named "response" but render always returns one.

render()

render(request, template_name, context=None, content_type=None, status=None, using=None)

Combines a given template with a given context dictionary and returns an HttpResponse object with that rendered text.

Django does not provide a shortcut function which returns a TemplateResponse because the constructor of TemplateResponse offers the same level of convenience as render().

(emphasis is mine)

So what you can do is update the generated response before it's returned to the user like so:

def thanks(request):
    order_number = Order.objects.latest('id').id
    response = render(request, 'thanks.html', dict(order_number=order_number))
    response.delete_cookie("item_id")
    return response

Upvotes: 7

Related Questions