How to get the currently logged in user's user id in Django?

前端 未结 5 1026
情书的邮戳
情书的邮戳 2020-12-12 11:34

How to get the currently logged-in user\'s id?

in models.py:

class Game(models.model):
    name = models.CharField(max_length=255)
    o         


        
5条回答
  •  不知归路
    2020-12-12 11:57

    I wrote this in an ajax view, but it is a more expansive answer giving the list of currently logged in and logged out users.

    The is_authenticated attribute always returns True for my users, which I suppose is expected since it only checks for AnonymousUsers, but that proves useless if you were to say develop a chat app where you need logged in users displayed.

    This checks for expired sessions and then figures out which user they belong to based on the decoded _auth_user_id attribute:

    def ajax_find_logged_in_users(request, client_url):
        """
        Figure out which users are authenticated in the system or not.
        Is a logical way to check if a user has an expired session (i.e. they are not logged in)
        :param request:
        :param client_url:
        :return:
        """
        # query non-expired sessions
        sessions = Session.objects.filter(expire_date__gte=timezone.now())
        user_id_list = []
        # build list of user ids from query
        for session in sessions:
            data = session.get_decoded()
            # if the user is authenticated
            if data.get('_auth_user_id'):
                user_id_list.append(data.get('_auth_user_id'))
    
        # gather the logged in people from the list of pks
        logged_in_users = CustomUser.objects.filter(id__in=user_id_list)
        list_of_logged_in_users = [{user.id: user.get_name()} for user in logged_in_users]
    
        # Query all logged in staff users based on id list
        all_staff_users = CustomUser.objects.filter(is_resident=False, is_active=True, is_superuser=False)
        logged_out_users = list()
        # for some reason exclude() would not work correctly, so I did this the long way.
        for user in all_staff_users:
            if user not in logged_in_users:
                logged_out_users.append(user)
        list_of_logged_out_users = [{user.id: user.get_name()} for user in logged_out_users]
    
        # return the ajax response
        data = {
            'logged_in_users': list_of_logged_in_users,
            'logged_out_users': list_of_logged_out_users,
        }
        print(data)
    
        return HttpResponse(json.dumps(data))
    
    

提交回复
热议问题