Keep Django session data after sign-in? Keep Django session data after sign-in? django django

Keep Django session data after sign-in?


Try writing your own SessionBackend that inherits from existing one and overrides the cycle_key method.

1 In your settings.py:

SESSION_ENGINE = 'my_app.session_backend'

2 my_app.session_backend.py:

from django.contrib.sessions.backends.db import SessionStore as DbSessionStoreclass SessionStore(DbSessionStore):    def cycle_key(self):        pass

cycle_key is beeing called in login view after authentication.

Let me now if it works ;)


Instead of disabling the cycle_key() (which is a security measure to avoid session fixation vulnerabilities), you could consider restoring the values through a decorator at the login and logout views. See:

https://stackoverflow.com/a/41849076/146289


I'm trying to do something similar. Django can change the session_key to mitigate session fixation vulnerabilities, so it's not suitable for a foreign key. I want something more permanent. So I'll just put the permanent identifier in request.session['visitor_id']:

from django.utils.crypto import get_random_stringimport stringVALID_KEY_CHARS = string.ascii_lowercase + string.digitsdef example_view(request):    if not request.session.get('visitor_id'):        self.request.session['visitor_id'] = get_random_string(32, VALID_KEY_CHARS)    # Now code the rest of the view, using the visitor_id instead of    # session_key for keys in your model.    # ...