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


124

如何获取当前登录用户的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=?)


1
@CiroSantilli新疆改造中心法轮功六四事件精确重复
Tessaracter

Answers:


209

首先要确保你有SessionMiddleware,并AuthenticationMiddleware添加到您的中间件MIDDLEWARE_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.


3
如果我们要将外键用户ID设置为当前登录用户ID的模型怎么办?
Krishnadas PC


2
请求来自哪里?
索伦

链接到User模型参考。
x-yuri


7

假设您是在视图中引用Django的Auth User

def game(request):
  user = request.user

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

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))
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.