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

la_f0ka picture la_f0ka · Feb 4, 2013 · Viewed 7.4k times · Source

django's User model has a last_login field, which is great if all the users were to log out each time they leave the site, but what if they don't?

How can I track when a user who never logged out and his activity on the site?

Answer

Aamir Adnan picture Aamir Adnan · Feb 4, 2013

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:

profiles/middleware.py:

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) \
                           .update(last_activity=timezone.now())

Add this middleware in your setting file:

MIDDLEWARE_CLASSES = (
    # other middlewares
    'myproject.profiles.middleware.UpdateLastActivityMiddleware',
)