3

I've been working on a small project and I've started wondering how to keep some data after the user logs in or logs out.

For example let's say that the user is adding items to his shopping cart and he is not logged in. Django sessions by default generate new session_id after the user logs in or logs out. When the user adds 5 products to his cart when and he logs in afterwards then his cart will be cleared.

How to implement an element of persistence in user data? For example should I use some signals or some sort of middleware to bind the cart from old to new session?

My main goal is to keep it safe so I don't want to disable some security mechanisms.

3
  • 1
    You can keep data using cookies or local storage stackoverflow.com/questions/3220660/local-storage-vs-cookies and send it via AJAX after user login
    – madzohan
    Oct 22, 2014 at 11:13
  • That seems to be fine solution. Cookies are easy to modify, so for cookie value I should set generate for example UUID? So it will be harder to steal the basket :)
    – Efrin
    Oct 22, 2014 at 11:18
  • Use can use ‘secure’ cookies. docs.djangoproject.com/en/dev/topics/security If a browser connects initially via HTTP, which is the default for most browsers, it is possible for existing cookies to be leaked. For this reason, you should set your SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE settings to True. This instructs the browser to only send these cookies over HTTPS connections. Note that this will mean that sessions will not work over HTTP, and the CSRF protection will prevent any POST data being accepted over HTTP.
    – madzohan
    Oct 22, 2014 at 11:33

2 Answers 2

2

You have to use the database-backed session. From the doc:

you need to add 'django.contrib.sessions' to your INSTALLED_APPS setting.

Once you have configured your installation, run manage.py migrate to install the single database table that stores session data.

Then you have to ensure that the session.flush() is not called in the logout/login process, witch implies avoid using the django.contrib.auth.logout() witch will call session.flush(), it is also called in django.contrib.login(). login and logout the user yourself to avoid losing the session data. source for login/logout.

1

The session is flushed at login/logout, as a security measure. If you want to retain some variables, you can use the solution at:

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

It basically involves backing up old values, and then restoring them in the new session.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.