Setting a cookie in a Django view
<p>I am trying to set a cookie in a view using the following code.</p>

<pre><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', {})
</code></pre>

<p>When the view is loaded, the console prints out <code>NOT SET</code>, 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 :/</p>

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

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

<p>You should capture the return value from render, and set the cookie on that:</p>

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

python django cookies