如何获取当前登录用户的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=?)
如何获取当前登录用户的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=?)
首先确保您已将中间件添加到您的SessionMiddleware
设置中。AuthenticationMiddleware
MIDDLEWARE_CLASSES
当前user
在request
对象中,您可以通过以下方式获取它:
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.
您可以使用以下代码访问当前登录用户:
request.user.id
假设您指的是 Django 的Auth User,在您看来:
def game(request):
user = request.user
gta = Game.objects.create(name="gta", owner=user)
我在 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))
这就是我通常在模板中获取当前登录用户及其 ID 的方式。
<p>Your Username is : {{user|default: Unknown}} </p>
<p>Your User Id is : {{user.id|default: Unknown}} </p>
对于模板内
这就是我通常在模板中获取当前登录用户及其 ID 的方式。
<p>Your Username is : {{user}} </p>
<p>Your User Id is : {{user.id}} </p>