如何在Django中获取当前登录的用户的用户ID? [英] How to get the currently logged in user's user id in Django?
问题描述
如何获取当前登录的用户ID?
How to get the currently logged-in user's id?
在 models.py
中:
in models.py
:
class Game(models.model):
name = models.CharField(max_length=255)
owner = models.ForeignKey(User, related_name='game_user', verbose_name='Owner')
$ c> views.py :
in views.py
:
gta = Game.objects.create(name="gta", owner=?)
推荐答案
首先确保你有 SessionMiddleware
和 AuthenticationMiddleware
添加到您的 MIDDLEWARE_CLASSES
设置中。
First make sure you have SessionMiddleware
and AuthenticationMiddleware
middlewares added to your MIDDLEWARE_CLASSES
setting.
当前用户
在请求
对象中,您可以通过以下方式获取它:
The current user
is in request
object, you can get it by:
def sample_view(request):
current_user = request.user
print current_user.id
request.user
会给你表示当前登录的用户的用户
对象。如果用户当前未登录,则 request.user
将被设置为 AnonymousUser
的实例。你可以用 is_authenticated()
告诉他们,如下所示:
request.user
will give you a User
object representing the currently logged-in user. If a user isn't currently logged in, request.user
will be set to an instance of AnonymousUser
. You can tell them apart with is_authenticated()
, like so:
if request.user.is_authenticated():
# Do something for authenticated users.
else:
# Do something for anonymous users.
这篇关于如何在Django中获取当前登录的用户的用户ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!