Django: get last user visit date

前端 未结 7 2228
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 04:28

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. Supp

7条回答
  •  生来不讨喜
    2020-12-13 05:16

    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)

提交回复
热议问题