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', {})
NOT SET
127.0.0.1:8000
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