I'm trying to develop login page for a web site. I stored users which logged on correctly to a cookie with set_cookie
. But I don't know how to delete the cookie. So, how can I delete the cookie to make a user log out?
Asked
Active
Viewed 3.5k times
32

Super Kai - Kazuya Ito
- 22,221
- 10
- 124
- 129

Nick Dong
- 3,638
- 8
- 47
- 84
-
check this question, it should help http://stackoverflow.com/questions/1275357/django-logoutredirect-to-home-page-delete-cookie here's documentation for django 1.4: https://docs.djangoproject.com/en/1.4/ref/request-response/#django.http.HttpResponse.delete_cookie – tony Jan 18 '13 at 14:54
-
Why aren't you using Django's auth framework? And even if you can't use that for some reason, why aren't you using the sessions framework rather than raw cookies? – Daniel Roseman Jan 18 '13 at 15:09
-
I am move the code from tornado to django. And the souce was developed using cookie. I dont want change a lot to the code. – Nick Dong Jan 19 '13 at 02:02
-
Yes, I have read the doc, and questions at [django-logoutredirect-to-home-page-delete-cookie](http://stackoverflow.com/questions/1275357/django-logoutredirect-to-home-page-delete-cookie) – Nick Dong Jan 19 '13 at 02:10
3 Answers
52
Setting cookies :
def login(request):
response = HttpResponseRedirect('/url/to_your_home_page')
response.set_cookie('cookie_name1', 'cookie_name1_value')
response.set_cookie('cookie_name2', 'cookie_name2_value')
return response
Deleting cookies :
def logout(request):
response = HttpResponseRedirect('/url/to_your_login')
response.delete_cookie('cookie_name1')
response.delete_cookie('cookie_name2')
return response

Dawn T Cherian
- 4,968
- 3
- 24
- 35
-
17deleting cookie this way still remains in browser, first hand experience :/ – vijay shanker Apr 27 '18 at 07:08
0
You can simply delete whatever you've stored in the cookie - this way, even though the cookie is there, it no longer contain any information required for session tracking and the user needs to authorize again.
(Also, this seems like a duplicate of Django logout(redirect to home page) .. Delete cookie?)
0
For example, you set cookies as shown below. *You must return the object otherwise cookies are not set to a browser and you can see my answer explaining how to set and get cookies in Django:
from django.shortcuts import render
def my_view(request):
response = render(request, 'index.html', {})
response.set_cookie('name', 'John') # Here
response.cookies['age'] = 27 # Here
return response # Must return the object
Then, you can delete the cookies with response.delete_cookie() as shown below. *You must return the object otherwise cookies are not deleted from a browser:
from django.shortcuts import render
def my_view(request):
response = render(request, 'index.html', {})
response.delete_cookie('name')
response.delete_cookie('age')
return response # Must return the object

Super Kai - Kazuya Ito
- 22,221
- 10
- 124
- 129