如何检查此用户是匿名用户还是系统上的用户?

TIM*_*MEX 62 python authentication django http

def index(request):
    the_user = request.user
Run Code Online (Sandbox Code Playgroud)

在Django中,我如何知道它是否是真正的用户?我试过了:

if the_user: 但是"AnonymousUser"即使没有人登录也是如此.所以,它总是返回true,这不起作用.

Dan*_*olo 104

你可以检查是否request.user.is_anonymous返回True.

  • 请注意,在`views.py`中你应该使用`request.user.is_anonymous()`因为它是一个函数,而在模板中你应该使用`{{user.is_anonymous}}` (18认同)
  • 看起来像在Django 1.9中它更像是`is_authenticated()`:请参阅https://docs.djangoproject.com/en/1.9/topics/auth/default/#authentication-in-web-requests (10认同)
  • 从Django 1.10开始,is_anonymous不再是一个方法(只是一个属性) (6认同)
  • 我必须同意Paolo Stefan的观点,您要使用的方法是`is_authenticated()`。另请参见http://thegarywilson.com/blog/2006/is_authenticated-vs-is_anonymous/ (2认同)
  • 当前的建议是使用`request.user.is_authenticated`,这是Django 1.10+中的一个属性,现在与`is_anonymous`相同-参见https://docs.djangoproject.com/en/dev/ref/contrib /auth/#django.contrib.auth.models.User.is_anonymous。请注意,如果您还使用Django Guardian,那么这些属性将不会发挥您认为的作用-请参阅https://django-guardian.readthedocs.io/en/stable/configuration.html (2认同)

小智 14

替代品

if user.is_anonymous():
    # user is anon user
Run Code Online (Sandbox Code Playgroud)

通过测试来查看用户对象的id是什么:

if user.id == None:
    # user is anon user
else:
    # user is a real user
Run Code Online (Sandbox Code Playgroud)

请参阅https://docs.djangoproject.com/en/dev/ref/contrib/auth/#anonymous-users

  • 似乎是一个坏主意.user.is_anonymous()将继续在新版本中工作,user.id可能不会,具体取决于将来的实现 (4认同)

Jef*_*wen 10

您应该检查 的值request.user.is_authenticated。它将返回True一个User实例和False一个AnonymousUser实例。

\n

一个答案建议使用is_anonymous,但django.contrib.auth 文档说 \xe2\x80\x9cyou 应该更喜欢is_authenticated使用is_anonymous xe2\x80\x9d。

\n


Har*_*lin 5

我遇到了类似的问题,只不过这是在 login_redirect_url 发送到的页面上。我必须输入模板:

{% if user.is_authenticated %}
    Welcome Back, {{ username }}
{% endif %}
Run Code Online (Sandbox Code Playgroud)