157

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

models.py

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

views.py

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

6 回答 6

269

首先确保您已将中间件添加到您的SessionMiddleware设置中。AuthenticationMiddlewareMIDDLEWARE_CLASSES

当前userrequest对象中,您可以通过以下方式获取它:

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

request.user会给你一个User代表当前登录用户的对象。如果用户当前未登录,request.user将设置为AnonymousUser. 您可以通过 field 将它们区分开来is_authenticated,如下所示:

if request.user.is_authenticated:
    # Do something for authenticated users.
else:
    # Do something for anonymous users.
于 2012-09-27T06:17:26.323 回答
26

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

request.user.id
于 2016-07-24T12:18:36.597 回答
8

假设您指的是 Django 的Auth User,在您看来:

def game(request):
  user = request.user

  gta = Game.objects.create(name="gta", owner=user)
于 2012-09-27T06:18:47.497 回答
0

我在 ajax 视图中写了这个,但它是一个更广泛的答案,给出了当前登录和注销用户的列表。

is_authenticated属性始终True为我的用户返回,我认为这是预期的,因为它只检查 AnonymousUsers,但如果您要开发一个需要显示登录用户的聊天应用程序,那么这证明是无用的。

这将检查过期会话,然后根据解码的_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))

于 2020-06-09T14:35:16.667 回答
0

这就是我通常在模板中获取当前登录用户及其 ID 的方式。

<p>Your Username is : {{user|default: Unknown}} </p>
<p>Your User Id is  : {{user.id|default: Unknown}} </p>
于 2020-12-18T04:42:04.950 回答
-1

对于模板内

这就是我通常在模板中获取当前登录用户及其 ID 的方式。

<p>Your Username is : {{user}} </p>
<p>Your User Id is  : {{user.id}} </p>
于 2020-10-22T17:05:22.293 回答