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?
-
check this question, it should help stackoverflow.com/questions/1275357/… here's documentation for django 1.4: docs.djangoproject.com/en/1.4/ref/request-response/…– tonyCommented Jan 18, 2013 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 RosemanCommented Jan 18, 2013 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 DongCommented Jan 19, 2013 at 2:02
-
Yes, I have read the doc, and questions at django-logoutredirect-to-home-page-delete-cookie– Nick DongCommented Jan 19, 2013 at 2:10
3 Answers
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
-
18deleting cookie this way still remains in browser, first hand experience :/ Commented Apr 27, 2018 at 7:08
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?)
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