如何获取经过身份验证的用户列表? [英] How to get the list of the authenticated users?

查看:123
本文介绍了如何获取经过身份验证的用户列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示已验证用户的列表。

I would like to display the list of the authenticated users.

在文档中: http ://docs.djangoproject.com/en/dev/topics/auth/


类models.User

is_authenticated()¶

始终返回True。这是一种告诉用户是否已通过身份验证的方式。 ...

class models.User
is_authenticated()¶
Always returns True. This is a way to tell if the user has been authenticated. ...

您可以在模板端知道当前 用户是否被认证: / p>

You can know on the template side is the current User is authenticated or not:


{%if user.is_authenticated%}
{%endif%}

{% if user.is_authenticated %} {% endif %}

但是我没有找到获得认证用户列表的方式。

But I didn't found the way the get the list of the authenticated users.

任何想法?

推荐答案

与rz的答案一致,您可以查询会话模型为非过期会话,然后将会话数据转换成用户。一旦你得到了,你可以把它变成一个模板标签,可以在任何给定的页面上呈现列表。

Going along with rz's answer, you could query the Session model for non-expired sessions, then turn the session data into users. Once you've got that you could turn it into a template tag which could render the list on any given page.

(这是所有未经测试,但希望会关闭

(This is all untested, but hopefully will be close to working).

获取所有登录用户...

Fetch all the logged in users...

from django.contrib.auth.models import User
from django.contrib.sessions.models import Session
from django.utils import timezone

def get_all_logged_in_users():
    # Query all non-expired sessions
    # use timezone.now() instead of datetime.now() in latest versions of Django
    sessions = Session.objects.filter(expire_date__gte=timezone.now())
    uid_list = []

    # Build a list of user ids from that query
    for session in sessions:
        data = session.get_decoded()
        uid_list.append(data.get('_auth_user_id', None))

    # Query all logged in users based on id list
    return User.objects.filter(id__in=uid_list)

使用这个,你可以制作一个简单的包含模板标签...

Using this, you can make a simple inclusion template tag...

from django import template
from wherever import get_all_logged_in_users
register = template.Library()

@register.inclusion_tag('templatetags/logged_in_user_list.html')
def render_logged_in_user_list():
    return { 'users': get_all_logged_in_users() }

logged_in_user_list.html

{% if users %}
<ul class="user-list">
    {% for user in users %}
    <li>{{ user }}</li>
    {% endfor %}
</ul>
{% endif %}

然后在您的主页上,您可以简单地使用它在哪里喜欢...

Then in your main page you can simply use it where you like...

{% load your_library_name %}
{% render_logged_in_user_list %}

编辑

2周的持续性问题,我假设任何想要拥有活跃用户类型的列表将使用 SESSION_EXPIRE_AT_BROWSER_CLOSE 设置,虽然我认识到这不是总是这样。

For those talking about the 2-week persistent issue, I'm assuming that anyone wanting to have an "active users" type of listing will be making use of the SESSION_EXPIRE_AT_BROWSER_CLOSE setting, though I recognize this isn't always the case.

这篇关于如何获取经过身份验证的用户列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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