How to delete cookies in Django?

37.9k views Asked by At

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?

3

There are 3 answers

0
SpankMe On

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
Super Kai - Kazuya Ito On

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
1
Dawn T Cherian On

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