33

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?

4

3 Answers 3

53

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
1
  • 18
    deleting cookie this way still remains in browser, first hand experience :/ Commented Apr 27, 2018 at 7: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

Not the answer you're looking for? Browse other questions tagged or ask your own question.