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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Better choice is to overload
login
method 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.