Tahmid Khan Nafee Tahmid Khan Nafee - 2 months ago 7
Python Question

Setting a cookie in a Django view

I am trying to set a cookie in a view using the following code.

def index(request):
resp = HttpResponse("Setting a cookie")
resp.set_cookie('name', 'value')
if 'name' in request.COOKIES:
print "SET"
else:
print "NOT SET"
return render(request, 'myapp/base.html', {})


When the view is loaded, the console prints out
NOT SET
, which means the cookie was not set. In every tutorial/doc, this seems to be the method used. However, it simply does not work for me :/

Any help? I am using Django 1.9.8, and I am running the app in my local server, or
127.0.0.1:8000
.

Answer

You're creating a response and setting a cookie on it, but then you don't actually do anything with that response. The render shortcut creates its own response which is the one actually sent back to the browser.

You should capture the return value from render, and set the cookie on that:

if 'name' in request.COOKIES:
    print "SET"
else:
    print "NOT SET"
resp = render(request, 'myapp/base.html', {})
resp.set_cookie('name', 'value')
return resp