Login

Keep Me Logged In for Django

Author:
krvss
Posted:
February 21, 2011
Language:
Python
Version:
1.2
Score:
1 (after 5 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

darek (on February 22, 2011):

Better choice is to overload login method and add one line which change cookie expiry time:

def login(request, ...):
    #...
    if request.POST.get('remember_me', None):
        request.session.set_expiry(settings.KEEP_LOGGED_DURATION)
    #...

In that case You don't have to write and use middlewares and other stuff.

#

artur_mwaigaryan (on November 8, 2011):

good point @ derek,ur solution is more efficient

#

Please login first before commenting.