Search code examples
pythonpython-3.xdjangodjango-viewsdjango-sessions

How to expire Django session in 5minutes?


I'm using this to login the user in:

def login_backend(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            request.session.set_expiry(300)
            return HttpResponseRedirect('/overview/')
        else:
            return HttpResponseRedirect('/login_backend/')
    else:
        return render_to_response('login_backend.html', context_instance=RequestContext(request))

I want session to expire after 5mins thus I added request.session.set_expiry(300) in the view above. But the session is never expiring. What am I doing wrong?


Solution

  • Update for Django 1.6

    The middleware code below is not working in Django 1.6 and above version because of json serializable. To make it work in all versions of Django, put the session serializer.

    settings.py

    #Handle session is not Json Serializable
    SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
    

    The above sample of serializer is for Django 1.6. Kindly search for other version. Thanks...

    Create middleware.py

    from datetime import datetime, timedelta
    from django.conf import settings
    from django.contrib import auth
    
    
    class AutoLogout:
      def process_request(self, request):
        if not request.user.is_authenticated() :
          #Can't log out if not logged in
          return
    
        try:
          if datetime.now() - request.session['last_touch'] > timedelta( 0, settings.AUTO_LOGOUT_DELAY * 60, 0):
            auth.logout(request)
            del request.session['last_touch']
            return
        except KeyError:
          pass
    
        request.session['last_touch'] = datetime.now()
    

    Update your settings.py:

    MIDDLEWARE_CLASSES = [
        .........................
    
        'app_name.middleware.AutoLogout', 
    ]
    
    # Auto logout delay in minutes
    AUTO_LOGOUT_DELAY = 5 #equivalent to 5 minutes