How does one enforce automatic logout due to inactivity in a Django application?

django-session-security notes the user activity based on server side and javascript events such as mousemove, keypress, etc, etc ... Also, it warns the user before expiring the session, and tries not to expire the session (where there any activity maybe from another browser tab ?).

Just install it and set settings.SESSION_SECURITY_EXPIRE_AFTER=1800. You could also set settings.SESSION_SECURITY_WARN_AFTER=1740.


You could update the session of an user when he accesses your site. For example in a middleware, this force session to be set again.

class ActivateUser(object):
    def process_request(self, request):
        if request.user.is_authenticated():
            request.session.modified = True

As an update on this topic. Django now has the SESSION_SAVE_EVERY_REQUEST setting which makes it a lot easier.