Very simple middleware to implement "remember me" functionality. Updates the session once per day to keep user logged.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
# The middleware from django.conf import settings from datetime import timedelta, date class KeepLoggedInMiddleware(object): def process_request(self, request): if not request.user.is_authenticated() or not settings.KEEP_LOGGED_KEY in request.session: return if request.session[settings.KEEP_LOGGED_KEY] != date.today(): request.session.set_expiry(timedelta(days=settings.KEEP_LOGGED_DURATION)) request.session[settings.KEEP_LOGGED_KEY] = date.today() return # Add to settings 1. unit_name.KeepLoggedInMiddleware to the bottom of MIDDLEWARE_CLASSES 2. KEEP_LOGGED_KEY = 'keep_me_logged' # session key KEEP_LOGGED_DURATION = 365 # in days # In your login view form = LoginForm(request.POST) if form.is_valid(): # some code if form.remember: request.session[settings.KEEP_LOGGED_KEY] = True
More like this
- Image compression before saving the new model / work with JPG, PNG by Schleidens 2 weeks ago
- Help text hyperlinks by sa2812 1 month, 1 week ago
- Stuff by NixonDash 3 months, 2 weeks ago
- Add custom fields to the built-in Group model by jmoppel 5 months, 2 weeks ago
- Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 9 months ago
Better choice is to overload
loginmethod and add one line which change cookie expiry time:
In that case You don't have to write and use middlewares and other stuff.
good point @ derek,ur solution is more efficient
Please login first before commenting.