user2906419
user2906419

Reputation: 9

Why variable is `None` in my case?

My code:

if not 'last_user_visit' in request.COOKIES:
    response.set_cookie('last_user_visit', now)
    last_visit = request.COOKIES.get('last_user_visit')
    print last_visit

Why last_visit is None in my case?

Upvotes: 0

Views: 47

Answers (2)

Nitish Kansal
Nitish Kansal

Reputation: 498

You have to send response first like Daniel have suggested, you are setting cookie on response and then you have to return it. So that from that time, whenever a request will come it will be holding that cookie and you can access it. you can create function like this:

def cookie_setter(request):
    '''Do your function task and create response object
    '''
    if not 'last_user_visit' in request.COOKIES:
        response.set_cookie('last_user_visit', now)
    return response

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599490

Because you're setting it on the response, and reading it back from the request. The version in request won't be updated until the response has been sent to the client and the next request has been received.

Upvotes: 1

Related Questions