0

I'm trying to create a cookie that has a specific expire time. I set it in my django view with the following code:

from datetime import datetime
response.set_cookie('cookie_name', 'cookie_value', expires=datetime.today() + timedelta(20*365), path='/path/to/cookie/')

I'm reading the value of the cookie using the jQuery Cookie plugin with the following code:

if ($.cookie("cookie_name") == "True") {
    $.cookie("cookie_name", "False");
}
else {
    $.cookie("cookie_name", "True");
}

My main problem is that the cookie seen as a Session cookie (as it is shown in the Chromium developer cookie list in the Resource tab, under Cookies. Why is the expire time for my cookie not being seen, or being reset? I can verify that the cookie is a session cookie because if I close the browser and reopen, the cookie is not there.

Update

I changed my cookie django code to the following, according to the answer in this post:

from datetime import datetime
max_age = 20*365*24*60*60 #twenty years
expires = datetime.strftime(datetime.utcnow() + timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT")
response.set_cookie(key='cookie_name', value='cookie_value', max_age=max_age, expires=expires, path='/path/to/cookie/')

According to Chromium, my cookie is still a session cookie.

Update 2

I also tried leaving out expires and only setting max_age, and I still get the same problem.

max_age = 20*365*24*60*60 #twenty years
expires = datetime.utcnow() + timedelta(seconds=max_age)
response.set_cookie(key='advisees', value=limit_to_advisees, expires=expires, path='/path/to/cookie/')

Django should calculate the max_age if it isn't provided. I'm really confused, here.

Community
  • 1
  • 1
Nathan Jones
  • 4,904
  • 9
  • 44
  • 70

3 Answers3

0

Set max_age as well. If not the browser will throw out the cookie when the session is complete. Or better yet, just specify max_age, not expires and expires will be calculated for you.

Upon further investigation, you are using a date object, expires requires a datetime object. So you'll want to do datetime.datetime.now() instead of datetime.date.today()

Chris Lacasse
  • 1,502
  • 10
  • 10
0

Using your Update 2 as a base I can't seem to replicate the problem.

What version of Django are you using? Both 1.3 and 1.3.1 are setting the cookie correctly for me.

Also have you tested it on other browsers? It seems like something more general is at hand here.

Dan
  • 1,721
  • 1
  • 9
  • 7
0

I was able to circumvent this problem by taking Django out of the equation and do everything cookie-related through jQuery Cookie. I think it may have something to do with the custom middleware I'm using, but I wasn't able to confirm this.

Nathan Jones
  • 4,904
  • 9
  • 44
  • 70