[Fixed]-Django: How can I check the last activity time of user if user didn't log out?


You need to have the last_activity field in the user profile (or custom user model). This field will be updated on every request. To achieve this you need to have custom middleware:


from django.utils import timezone

from myproject.profiles.models import Profile

class UpdateLastActivityMiddleware(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
        assert hasattr(request, 'user'), 'The UpdateLastActivityMiddleware requires authentication middleware to be installed.'
        if request.user.is_authenticated():
            Profile.objects.filter(user__id=request.user.id) \

Add this middleware in your setting file:

    # other middlewares


i think in 2022 this will satisfy what you need also i did this and worked for me but the answer didnt.

put LastActivityTraceMiddleware after AuthenticationMiddleware in settings.py.

from django.utils.timezone import now
from .... import MemberEntity

class LastActivityTraceMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)

        member: MemberEntity = request.user
        if member.is_authenticated:
            member.last_login = now()
        return response


I know the question is old … and surely it has already been solved …
but here is my contribution …
In new versions of django you can use:

"Session Time" -> Used in configuration file. "settings.py"

If the user closes the browser, the session ends and must be logged in again …


If the user does not close the browser, you can set a time limit for the session …


For "SESSION_COOKIE_AGE" if I remember correctly it’s defined in seconds.
You can see more here
Recommended reading is also django’s own documentation about sessions

Leave a comment