[英]How to check whether a user is online in django template?
在模板中,当我使用时
{% if topic.creator.is_authenticated %}
Online
{% else %}
Offline
{% endif %}
用户结果总是在线,即使他们刚刚退出。 所以我想知道如何正确检查在线用户?
感谢这篇优秀的博文,稍作修改后,我想出了一个更好的解决方案,它使用了memcache,因此每个请求的延迟更少:
在models.py中添加:
from django.core.cache import cache
import datetime
from myproject import settings
并将这些方法添加到userprofile类:
def last_seen(self):
return cache.get('seen_%s' % self.user.username)
def online(self):
if self.last_seen():
now = datetime.datetime.now()
if now > self.last_seen() + datetime.timedelta(
seconds=settings.USER_ONLINE_TIMEOUT):
return False
else:
return True
else:
return False
在userprofile文件夹中添加此middleware.py
import datetime
from django.core.cache import cache
from django.conf import settings
class ActiveUserMiddleware:
def process_request(self, request):
current_user = request.user
if request.user.is_authenticated():
now = datetime.datetime.now()
cache.set('seen_%s' % (current_user.username), now,
settings.USER_LASTSEEN_TIMEOUT)
在settings.py中添加'userprofile.middleware.ActiveUserMiddleware',
添加到MIDDLEWARE_CLASSES
并添加:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
# Number of seconds of inactivity before a user is marked offline
USER_ONLINE_TIMEOUT = 300
# Number of seconds that we will keep track of inactive users for before
# their last seen is removed from the cache
USER_LASTSEEN_TIMEOUT = 60 * 60 * 24 * 7
并在profile.html中:
<table>
<tr><th>Last Seen</th><td>{% if profile.last_seen %}{{ profile.last_seen|timesince }}{% else %}awhile{% endif %} ago</td></tr>
<tr><th>Online</th><td>{{ profile.online }}</td></tr>
</table>
而已!
要在控制台中测试缓存,以确保memcache正常工作:
$memcached -vv
$ python manage.py shell
>>> from django.core.cache import cache
>>> cache.set("foo", "bar")
>>> cache.get("foo")
'bar'
>>> cache.set("foo", "zaq")
>>> cache.get("foo")
'zaq'
您可以为每个用户提供一个整数字段,说明用户当前登录的会话数。 每次用户登录时,您可以将其增加1,并在用户注销时将其减少1。
{% if topic.creator.login_count %}
Online
{% else %}
Offline
{% endif %}
这是解决此问题的简单方法。 您可以定期通过ajax请求刷新此数据。
正如文件所说:
即使通常你会检查request.user上的is_autheticated属性以确定它是否已被AuthenticationMiddleware(代表当前登录的用户)填充,你应该知道任何User实例的这个属性为True。
所以要检查用户是否在线我会做这样的事情:
models.py
class Profile(models.Model):
user = models.OneToOneField(User, related_name='profile')
is_online = models.BooleanField(default=False)
views.py
from django.contrib.auth.signals import user_logged_in, user_logged_out
from django.dispatch import receiver
@receiver(user_logged_in)
def got_online(sender, user, request, **kwargs):
user.profile.is_online = True
user.profile.save()
@receiver(user_logged_out)
def got_offline(sender, user, request, **kwargs):
user.profile.is_online = False
user.profile.save()
然后在您的模板中,您将检查用户是否在线:
{% if user.profile.is_online %}
Online
{% else %}
Offline
{% endif %}
不要忘记将用户实例返回到模板,以便user.profile.is_online
可以正常工作。
Django文档中描述了用户似乎始终在线的原因:
is_authenticated()
- 始终返回
True
...这是一种判断用户是否已经过身份验证的方法。 这并不意味着任何权限,也不会检查用户是否处于活动状态或是否具有有效会话。
您可以通过多种方式实现此目标,但没有一种方法可以“内置”。
此问题涵盖用户的上一个活动时间 ,您可以使用它来检查用户在过去几分钟内是否处于活动状态。
或者,您可以查询会话表以检查用户是否具有活动会话,但如果您有较长的会话超时,则可能不准确。
是的,它确实。 但检查用户是否登录的正确方法是使用:request.user.is_authenticated。 如果此人以其他方式登录,则返回True。
例如:
在模板中:
{% if request.user.is_authenticated ==True %}
do something awesome.
在视图中将请求传递到模板中。
return render('url/filename.html',{'any variable name':request})
首先通过运行安装django-online-users
pip install django-online-users
然后在你的settings.py中
INSTALLED_APPS = [
...
'online_users',]
MIDDLEWARE_CLASSES = (
...
'online_users.middleware.OnlineNowMiddleware',)
然后在你的意见
import online_users.models
def see_users(self):
user_status = online_users.models.OnlineUserActivity.get_user_activities(timedelta(seconds=60))
users = (user for user in user_status)
context = {"online_users"}`
例如,将上下文传递给模板
{% for user in users %}
{{user.user}}
{% endfor %}
这将输出过去60秒内处于活动状态和在线状态的用户
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.