Django:如果用户没有注销,我如何检查用户的最后活动时间? [英] Django: How can I check the last activity time of user if user didn't log out?

查看:133
本文介绍了Django:如果用户没有注销,我如何检查用户的最后活动时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

django的用户模型有一个 last_login 字段,这是非常好的,如果所有的用户每次离开网站注销,但如果不这样做呢?



如何跟踪何时未登录的用户和他的活动在网站上?

解决方案

您需要在用户配置文件(或自定义用户模型)中具有 last_activity 字段。每个请求都会更新此字段。要实现这一点,您需要有自定义中间件:



个人资料/ middleware.py:

 code> 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'),'UpdateLastActivityMiddleware需要安装认证中间件'
if request.user.is_authenticated() :
Profile.objects.filter(user__id = request.user.id)\
.update(last_activity = timezone.now())

在设置文件中添加这个中间件:

  MIDDLEWARE_CLASSES = 
#其他中间件
'myproject.profiles.middleware.UpdateLastActivityMiddleware',


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?

解决方案

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',
)

这篇关于Django:如果用户没有注销,我如何检查用户的最后活动时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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