Search code examples
pythondjangocookieshttpresponsesetcookie

Problem setting cookies in django


I am trying to set and read cookies using the following code

cookie_name = 'fbs_%s' % practice_settings.PRACTICE_ID
response = HttpResponse( "blah" )
response.set_cookie( cookie_name, "cookie_value" )
value = request.COOKIES.get(cookie_name)
print value

For some reason value remains None. Is there something simple that I am missing here? Thanks in advance


Solution

  • You are setting the cookie in the response object (response.set_cookie( cookie_name, "cookie_value")), but trying to retrieve it from the request object (request.COOKIES.get(cookie_name)).

    When you set a cookie in the response it will not automatically be populated in the original request. It will be available in the following request of the view you call after the one you set the cookie.