Django:获取最后一个用户的访问日期 [英] Django: get last user visit date

查看:737
本文介绍了Django:获取最后一个用户的访问日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django中,我们可以通过使用 Auth.User.last_login 获得用户上次登录的时间。只有当用户使用用户名/密码登录时才更新。假设用户已经登录,认证信息保存在cookie中,因此可以访问该站点而不登录。我们如何获取用户以前访问过的日期?

解决方案

示例模型:


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

将为所有登录用户执行的示例中间件:



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $


$ process $ ):
如果request.user.is_authenticated():
#请求完成处理后更新上次访问时间。
User.objects.filter(pk = request.user.pk).update(last_visit = now())
返回响应

将新的中间件添加到您的settings.py:

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

警告:未经测试,但不需要安装外部程序包,只有5行代码。



有关中间件自定义用户模型(自Django 1.5起)


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.

解决方案

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)

这篇关于Django:获取最后一个用户的访问日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆