更新时间:2022-06-26 07:49:15
首先确保你有 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.