By default, Django sessions are set to 2 weeks (SESSION_COOKIE_AGE defaults to 1209600 seconds) and will not expire when the browser is closed (SESSION_EXPIRE_AT_BROWSER_CLOSE defaults to False).
If you’d like to offer the user a ‘remember me’ option when logging in, you’ll need to expire the session when the browser is closed if the user doesn’t check the box. Simply add the following to your form class:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
remember_me = forms.BooleanField(required=False, widget=forms.CheckboxInput()) | |
if not self.cleaned_data.get('remember_me'): | |
self.request.session.set_expiry(0) |
Note: This makes use of the request object in the form via this technique.
This works as expected in most browsers but Chrome likes to hold on to cookies. More on this issue can be found in the Django docs and Stack Exchange.