[英]How can I know if a specific user, not the current requesting user, is logged in Django?
How can I know if a specific user is logged in Django (not the currently requesting user)? 如何知道特定用户是否登录Django(不是当前请求的用户)?
I tried this: 我试过这个:
user = User.objects.get(username="jon")
if user.is_authenticated():
print "user logged"
But this always returns True
if the username
matched. 但如果
username
匹配,则总是返回True
。
The short answer is you can't; 简短的回答是你不能; at least not with anything built-in to Django.
至少没有任何内置于Django的内容。 To know if any user in the database is logged in you essentially are asking if the user is tied to an active session.
要知道数据库中的任何用户是否已登录,您实际上是在询问用户是否与活动会话绑定。 But you cannot query the session table (short of querying all active sessions) for the user id since this information is stored as pickled data.
但是您无法查询会话表(缺少查询所有活动会话)的用户ID,因为此信息存储为pickle数据。 And even if you did this is not entirely meaningful depending on how long the session cookie lasts (default 2 weeks).
即使你这样做也不完全有意义,具体取决于会话cookie持续多长时间(默认为2周)。
So what can you do? 所以,你可以做什么? One thing you can query about the user is the last time they logged in. For instance you could get user which last logged in less than 10 minutes ago:
您可以查询有关用户的一件事是他们最后一次登录。例如,您可以在不到10分钟前获得上次登录的用户:
from datetime import datetime, timedelta
from django.contrib.auth.models import User
cutoff = datetime.now() - timedelta(minutes=10)
active = User.objects.filter(last_login__gt=cutoff)
Another thing you can do is track this on your own. 您可以做的另一件事就是自己跟踪。 In fact there is an app which does just that called django-tracking .
事实上,有一个应用程序,它只是做django跟踪 。
No in-built method exists to do what you're looking for, however there is an app that you can plugin to your project that lets you do what you want. 没有内置的方法来执行您正在寻找的内容,但是有一个应用程序,您可以插入到您的项目,让您做你想要的。 It's called django-tracking and you can find it here: https://github.com/codekoala/django-tracking
它被称为django-tracking,你可以在这里找到它: https : //github.com/codekoala/django-tracking
EDIT Whoops! 编辑哎呀! I got beat to it, but basically what Mark Lavin said.
我被击败了,但基本上是Mark Lavin所说的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.