0

I am trying to set a cookie in a Django view. Something like this:

def my_view(request):
    response = HttpResponse('Setting a cookie')
    if 'my_cookie' in request.COOKIES:
        return HttpResponse('Cookie found.')
    else:
        response.set_cookie('my_cookie', 'value')
        return HttpResponse('Cookie set.')

In my mind, how it should work is this: on the first load, the cookie is not found, so its set and 'Cookie set.' is returned. If I reload the page, the cookie should be found, since it has been set already, so 'Cookie found.' is returned.

However, every time I reload, I get 'Cookie set.' for some reason. Any help? Thanks.

EDIT

I edited my code according the first comment:

def my_view(request):
    response = HttpResponse('Setting a cookie')
    if 'my_cookie' in request.COOKIES:
        print 'Cookie found.'
        response = HttpResponse(request.COOKIES['my_cookie'])
        return response
    else:
        print 'Cookie set.'
        response.set_cookie('my_cookie', 'value')
        response = HttpResponse('value')
        return response

I am returning the object that is being used to set the cookie. I am only trying to get the value. However, in my console, I always get 'Cookie set.', why is that?

darkhorse
  • 8,192
  • 21
  • 72
  • 148

0 Answers0