如何获取当前登录用户的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=?)
答案 0 :(得分:158)
首先确保您的SessionMiddleware
设置中添加了AuthenticationMiddleware
和MIDDLEWARE_CLASSES
个中间件。
当前user
位于request
对象中,您可以通过以下方式获取:
def sample_view(request):
current_user = request.user
print current_user.id
request.user
将为您提供代表当前登录用户的User
对象。如果用户当前未登录,则request.user
将设置为AnonymousUser
的实例。您可以使用is_authenticated()
区分它们,如下所示:
if request.user.is_authenticated():
# Do something for authenticated users.
else:
# Do something for anonymous users.
答案 1 :(得分:14)
您可以使用以下代码访问当前登录用户:
request.user.id
答案 2 :(得分:7)
假设您在您的视图中指的是Django的Auth User:
def game(request):
user = request.user
gta = Game.objects.create(name="gta", owner=user)
答案 3 :(得分: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))
答案 4 :(得分:0)
用于模板内
这通常是我在模板中获取当前登录用户及其ID的方式。
<p>Your Username is : {{user}} </p>
<p>Your User Id is : {{user.id}} </p>
答案 5 :(得分:0)
这通常是我在模板中获取当前登录用户及其ID的方式。
<p>Your Username is : {{user|default: Unknown}} </p>
<p>Your User Id is : {{user.id|default: Unknown}} </p>