Change django session key during authentication

I have a Django application that records the selection of products for users as authenticated users. My intention is to use the request.session.session_key variable to bind anonymous data to the user if they decide to register later, a la this post:

Django saving anonymous user data

However, it seems that the session key changes when the user registers / registers, so the session key can no longer be associated with the user. This is the correct behavior of the Django session frame. Is there a reliable way to achieve the functionality I'm looking for?

Any help is greatly appreciated.

+8
django django-admin django-views
source share
2 answers

In settings.py

SESSION_ENGINE = 'youapp.session_backend'

in youapp directory in session_backend.py file

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

And the session did not change after logging in

+10
source share

While the approach suggested by nnmware may work for this particular case, there is a better one.

Instead of doing anything inside cycle_key , we should call the super method and then save the session.

Because if you look inside the original cycle_key function, you will see that the data from the old session is copied to the new, but not really saved.

In settings.py

 SESSION_ENGINE = 'yourapp.session_backend' 

Make sure that SESSION_ENGINE points to the module (.py file), but not to the base class!

Now, in your 'yourapp / session_backend.py', do the following:

 from django.contrib.sessions.backends.db import SessionStore as DbSessionStore class SessionStore(DbSessionStore): def cycle_key(self): super(SessionStore, self).cycle_key() self.save() 
+3
source share

All Articles