简体   繁体   English

如何获取Django中当前登录用户的用户id?

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

How to get the currently logged-in user's id?如何获取当前登录用户的id?

in models.py :models.py中:

class Game(models.model):
    name = models.CharField(max_length=255)
    owner = models.ForeignKey(User, related_name='game_user', verbose_name='Owner')

in views.py :views.py中:

gta = Game.objects.create(name="gta", owner=?)

First make sure you have SessionMiddleware and AuthenticationMiddleware middlewares added to your MIDDLEWARE_CLASSES setting.首先确保您已将SessionMiddlewareAuthenticationMiddleware中间件添加到您的MIDDLEWARE_CLASSES设置中。

The current user is in request object, you can get it by:当前userrequest对象中,您可以通过以下方式获取它:

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. request.user会给你一个代表当前登录User对象。 If a user isn't currently logged in, request.user will be set to an instance of AnonymousUser .如果用户当前未登录, request.user将设置为AnonymousUser的实例。 You can tell them apart with the field is_authenticated , like so:您可以通过字段is_authenticated区分它们,如下所示:

if request.user.is_authenticated:
    # Do something for authenticated users.
else:
    # Do something for anonymous users.

您可以使用以下代码访问当前登录用户:

request.user.id

Assuming you are referring to Django's Auth User , in your view:假设您指的是 Django 的Auth User ,在您看来:

def game(request):
  user = request.user

  gta = Game.objects.create(name="gta", owner=user)

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.我在 ajax 视图中写了这个,但它是一个更广泛的答案,给出了当前登录和注销的用户列表。

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. is_authenticated属性总是为我的用户返回True ,我认为这是预期的,因为它只检查 AnonymousUsers,但是如果您要开发一个需要显示登录用户的聊天应用程序,那证明是无用的。

This checks for expired sessions and then figures out which user they belong to based on the decoded _auth_user_id attribute:这会检查过期的会话,然后根据解码的_auth_user_id属性找出它们属于哪个用户:

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))

This is how I usually get current logged in user and their id in my templates.这就是我通常在模板中获取当前登录用户及其 ID 的方式。

<p>Your Username is : {{user|default: Unknown}} </p>
<p>Your User Id is  : {{user.id|default: Unknown}} </p>

Just go on your profile.html template and add a HTML tag named paragraph there,只需 go 在您的个人资料.html 模板中,并在其中添加一个名为 paragraph 的 HTML 标签,

<p>User-ID: {% user.id %}</p>

FOR WITHIN TEMPLATES用于模板内

This is how I usually get current logged in user and their id in my templates.这就是我通常在模板中获取当前登录用户及其 ID 的方式。

<p>Your Username is : {{user}} </p>
<p>Your User Id is  : {{user.id}} </p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM