How to expire session on browser close in django
django employs cookies to track the user session. settings.SESSION_COOKIE_AGE defines the session expiration age in seconds. So, the user logs in once and can stay logged in for hours (even days).
But what if a user wants the session to expire as soon as the browser is closed? This is perfectly desirable for users on public/shared computers.
As always, django comes for rescue with a 5 minutes solution 🙂 . There is a variable SESSION_EXPIRE_AT_BROWSER_CLOSE in settings.py, if set to True, django will expire session as users close the browser window.
So you have two options,
1. Policy 1: Keep user logged in as required
2. Policy 2: Expire the session when user closes the browser
Ideally, the user should be able to choose if he wants to remain logged in or not. Fortunately, django comes equipped to handle this issue. You can utilize session.set_expiry to determine the policy. Here is how it works,
1. Add a ‘Remember me’ checkbox in login form
2. If unchecked, call request.session.set_expiry(0)
And you are all good to go 🙂 . You can call request.session.get_expire_at_browser_close() at anytime to
check which policy user has opted for
Читайте також:
- Проксі моделі Django
- django custom admin
- django-stdimage traceback "The '%s' attribute has no file associated with it"
- Fix Django 1.4 admin_site ForeignKeyRawIdWidget issue
- Retrieving elements in a specific order in django
- Django mongoengine cache backend
- django postgresql та SCHEMA для таблиць
- django-mptt деревоподібний select
- Django defer, only
- Django suit admin inline pagination