Django: get last user visit date

django

Solution

Example model:

class User(models.Model):
    last_visit = models.DateTimeField(...)
    ...

Example middleware which will be executed for all logged-in users:

from django.utils.timezone import now

class SetLastVisitMiddleware(object):
    def process_response(self, request, response):
        if request.user.is_authenticated():
            # Update last visit time after request finished processing.
            User.objects.filter(pk=request.user.pk).update(last_visit=now())
        return response

Add the new middleware to Your settings.py:

MIDDLEWARE_CLASSES = (
    ...
    'path.to.your.SetLastVisitMiddleware',
    ...
)

Warning: not tested, but doesn't require external packages to be installed and it's only 5 lines of code.

See more in the docs about Middleware and custom user models (since Django 1.5)

Problem

In Django, we can get the time user last logged in by using `Auth.User.last_login`. That is only updated when the user logs in using his username/password. Suppose the user is already logged in and the authentication information is saved in a cookie, therefore is able to access the site without logging in. How can we get the date the user previously visited the site? This would be useful for queries such as getting the number of new records since the last visit.

Original source

Related problems