Search code examples
djangotemplatessessiontimercountdown

Django session countdown timer


I have it in my login screen:

SESSION_COOKIE_AGE = 1200 # 20 minutes

And I want to show the remaining time in my template

Does anyone know a good or middleware package for django to add a timer remaining to end the login session. I did not think anything built with Django, just javascript solutions. Thank U.


Solution

  • First you need to get the session key from the request. Then, it's easy to get the session object and query its age:

    from django.contrib.sessions.models import Session
    
    session_key = request.COOKIES["sessionid"]
    session = Session.objects.get(session_key=session_key)
    
    remaining_seconds = session.get_expiry_age()
    

    Then you must add remaining_seconds variable to your template context or maybe better write a context processor so this variable is available at every template.