Search code examples
djangodjango-viewsdjango-sessions

django- how to have a common list for anonymous and logged in user


i have a list on my website which remains same for both anonymous and logged-in users. I use session dictionary to store the data.But when I logout I lose the session values as the django.contrib.auth.views.logout uses session.flush().....If I make a custom logout by removing the sessions.flush() ,I am not able to log-out. Can someone tell me how override the flush()..or some other by which we can create a common list for anonymous and logged-in users.


Solution

  • Lets say you have a list called 'user_list'

    def logout_view(logout):
        # Do whatever pre conditions you have here.
        my_list = request.session['user_list']
        logout(request)
        # Now Django would have flushed your previous sessions and created a new session.
        request.session['user_list'] = my_list
        return HttpResponse() # Or render to response i.e whatever you do.
    

    Now make sure that a session is being created for anonymous user also. And rest everything will work. Hope it does for you.