[Django]-Django logout(redirect to home page) .. Delete cookie?

30👍

Like jobscry said, logout() cleans session data, but it looks like you have set your own cookies too.

You could wrap auth logout view, which will return a HttpResponse:

def logout_user(request):
     response = logout(request, next_page=reverse('app.home.views.home'))
     response.delete_cookie('user_location')
     return response

Or if you’re just using the logout method as opposed to the view, you can use the return value for the redirect() method you have (which I assume returns a HttpResponse too).

def logout_user(request):
     logout(request)
     response = redirect('app.home.views.home')
     response.delete_cookie('user_location')
     return response

1👍

according to http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.logout

Changed in Django 1.0: Calling logout() now cleans session data.

1👍

Hope this helps:
delete cookie when caling "/clear-cookies"

location.href = '/clear-cookies';
  1. Define a method in views.py:

    def clear_cookies(request):
        response = HttpResponseRedirect('/')
        response.delete_cookie('_gat', domain='example.com')
        response.delete_cookie('_ga', domain='example.com')
        response.delete_cookie('_gid', domain='example.com')
        return response
    
  2. Add the path and method to your urls.py:

    url(r'^clear-cookies', clear_cookies),
    

0👍

This is slightly tangential, but maybe helpful to others in a similar situation.

If you are setting cookies that need to be deleted when the user logs out, maybe you shouldn’t be using cookies in the first place. For that use case, it’s much better to use session data instead. Like:

request.session['myKey'] = myValue

retrievedValue = request.session.get('myKey')

From the docs: "The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies".

Using session data is more secure and more performant than setting cookies, because the data stays on the server side.

The only use case where I would recommend setting your own cookies is if you need to store information that persists beyond a session (say you want to store preferences across sessions for a visitor who does not sign in).

Leave a comment