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

前端 未结 5 1015
情书的邮戳
情书的邮戳 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:44

    You can access Current logged in user by using the following code:

    request.user.id
    
    0 讨论(0)
  • 2020-12-12 11:46

    Assuming you are referring to Django's Auth User, in your view:

    def game(request):
      user = request.user
    
      gta = Game.objects.create(name="gta", owner=user)
    
    0 讨论(0)
  • 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))
    
    
    0 讨论(0)
  • 2020-12-12 12:05

    FOR WITHIN TEMPLATES

    This is how I usually get current logged in user and their id in my templates.

    <p>Your Username is : {{user}} </p>
    <p>Your User Id is  : {{user.id}} </p>
    
    0 讨论(0)
  • 2020-12-12 12:06

    First make sure you have SessionMiddleware and AuthenticationMiddleware middlewares added to your MIDDLEWARE_CLASSES setting.

    The current user is in request object, you can get it by:

    def sample_view(request):
        current_user = request.user
        print current_user.id
    

    request.user will give you a User object representing the currently logged-in user. If a user isn't currently logged in, request.user will be set to an instance of AnonymousUser. You can tell them apart with the field is_authenticated, like so:

    if request.user.is_authenticated:
        # Do something for authenticated users.
    else:
        # Do something for anonymous users.
    
    0 讨论(0)
提交回复
热议问题