How to update a cookie in Django

15,840

Solution 1

At some point, for a new user, you should set the cookie. Cookie expire time is usually a per user case. In Django, you can set the cookie age with the following code:

response = redirect('somewhere') # replace redirect with HttpResponse or render
response.set_cookie('cookie_name', 'cookie_value', max_age=1000)

The above cookie will expire after 1000s in a user's browser.

There's also an expires attribute where you can specify an expire date.

Reference: https://docs.djangoproject.com/en/2.0/ref/request-response/#django.http.HttpResponse.set_cookie

EDIT

From the django source code, try the following:

response = redirect('somewhere') # replace redirect with HttpResponse or render
response.cookies['cookie_name']['expires'] = datetime.today() + timedelta(days=1)

Expire the above 1 day from today.

Solution 2

Accessing cookies: request.COOKIES[..]

Setting cookies: response.set_cookie()

More informations here: django book: Sessions...

Share:
15,840

Related videos on Youtube

mistalaba
Author by

mistalaba

Traveling Django developer

Updated on February 28, 2020

Comments

  • mistalaba
    mistalaba about 4 years

    In other languages, it's very easy to update for example the expire date in a cookie, but I can't for my life figure out how to do it in Django!

    The reason for updating the expire date instead of setting a new cookie is so I don't have to do a database call on every page.

    EDIT: Thanks for all the answers, but it seems to be some confusion about what I'm trying to accomplish, so I'll try to be more precise: SETTING or GETTING a cookie is not the question. What I would like to know is how to UPDATE an already set cookie. Sorry for the misunderstanding!

  • mistalaba
    mistalaba about 13 years
    Well, I want to explore a solution that doesn't involve setting the cookie again. Could of course go the js way, but it doesn't feel very...pythonic :)
  • mistalaba
    mistalaba about 13 years
    I already set the cookie, the question is how to update an already set cookie?
  • mistalaba
    mistalaba about 13 years
    Is it possible to modify an accessed cookie a la request.COOKIES['mycookie'].expire = etc?
  • mistalaba
    mistalaba about 13 years
    I tried your edited response, but it seems that you cannot do that with the standard cookies (getting KeyError 'cookie_name', even if you previously set that cookie). After looking into this, it seems it might work if you use django.http.SimpleCookie(). I'll investigate further.. thanks for the lead!
  • baklarz2048
    baklarz2048 about 13 years
    Yes look at justcramer.com/2007/12/20/… you can modify to change expire time

Related