mistalaba
mistalaba

Reputation: 558

How to update a cookie in 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!

Upvotes: 14

Views: 19258

Answers (5)

KhacNha
KhacNha

Reputation: 327

More secure cookies with Django >= 4.2:

# set cookie with **Request**:
request.get_signed_cookie("name")

# get cookie with **Response**:
response = render(request, "index.html")
response.set_signed_cookie("name", "value")
return response

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

Upvotes: 0

oruchkin
oruchkin

Reputation: 1295

this is how you can render a template with any context, and changing cookie

    context = {"any_context_key_1":"value_1", "key_2": "value_2"}
    response = render(request, 'index.html', context)
    response.set_cookie("this_is_cookies_key", "this_is_its_value", max_age=None)
    return response 

Upvotes: 0

Thierry Lam
Thierry Lam

Reputation: 46254

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.

Upvotes: 21

baklarz2048
baklarz2048

Reputation: 10938

Three ways: 1)

response = render_to_response(template_name, {'data':'data'})
response.set_cookie("cookie_name","test_value")
return response

2Midellware: http://justcramer.com/2007/12/20/set-cookies-without-a-response-in-django/

3) javascript in template

Upvotes: 0

manji
manji

Reputation: 47968

Accessing cookies: request.COOKIES[..]

Setting cookies: response.set_cookie()

More informations here: django book: Sessions...

Upvotes: 3

Related Questions