Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a cookie in Django

Tags:

cookies

django

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!

like image 539
mistalaba Avatar asked Apr 08 '11 12:04

mistalaba


People also ask

How do I use cookies in Django?

A Django cookie attribute can perform one of two actions. It can drop a cookie in a user’s computer (set) and then access those cookies (get). Let’s look at both the methods here. This cookie attribute creates a cookie, which is then sent by the server to the user browser to store information. The syntax for set_cookie () is:

What happens when cookie expires in Django httpresponse?

When the cookie expires, it is removed from the browser. The Django HttpResponse object has a set_cookie () method. name: Name of the cookie. value: Value you want to store in the cookie. You can set int or string but it will return string.

What happens when a user logs out of Django?

When a user logs in, Django adds a row to the django_session database table. Django updates this row each time the session data changes. If the user logs out manually, Django deletes the row. But if the user does not log out, the row never gets deleted. A similar process happens with the file backend.

What is session_expire_at_browser_Close in Django?

If SESSION_EXPIRE_AT_BROWSER_CLOSE is set to True, Django will use browser-length cookies – cookies that expire as soon as the user closes their browser. Use this if you want people to have to log in every time they open a browser.


1 Answers

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.

like image 79
Thierry Lam Avatar answered Sep 23 '22 19:09

Thierry Lam