Search code examples
djangopython-3.xdjango-sessions

Django create session which does not destroy after logout


In my django project I want a session which only destroys after a certain time, for that I set the expire time but session is also destroying after logout.

Basically what I want to a session which is not effected by any login/logout activity.

I search it for but not found any solution, anyone help me.


Solution

  • Well, when you call logout, it flushes the session. If you want to keep that data, then you need to define your own logout functionality. You can try like that:

    from django.contrib.auth import logout
    
    def logout(request):
        your_data = request.session.get('your_key', None)
        current_expiry = request.session.get('_session_expiry')
        logout(request)
        if your_data:
            request.session['your_key'] = your_data
            if current_expiry:
               request.session['_session_expiry'] = current_expiry
    

    FYI Its an untested code. Also, Maybe its better if you don't use session for storing data which should last after logout. You can use redis or any temporary storage for this.