How to get the list of the authenticated users?

前端 未结 4 739
温柔的废话
温柔的废话 2020-11-29 17:14

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

On the documentation: http://docs.djangoproject.com/en/dev/topics/auth/

class mo

4条回答
  •  攒了一身酷
    2020-11-29 17:50

    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 %}
    
      {% for user in users %}
    • {{ user }}
    • {% endfor %}
    {% endif %}

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

    {% load your_library_name %}
    {% render_logged_in_user_list %}
    

    EDIT

    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.

提交回复
热议问题