如何检查用户是否已登录(如何正确使用user.is_authenticated)?

我正在寻找这个网站,但似乎无法弄清楚如何做到这一点,因为它不工作。我需要检查当前站点用户是否已登录(已验证),并且正在尝试:

request.user.is_authenticated

尽管确定用户已经登录,但它只返回:

>

我能够做其他的请求(从url上面的第一部分),比如:

request.user.is_active

返回一个成功的响应。

331739 次浏览

Django 1.10+更新

is_authenticated现在是Django 1.10中的属性

if request.user.is_authenticated:
# do something if the user is authenticated

注意:这个方法在Django 2.0中被删除了。

对于Django 1.9及以上版本

is_authenticated是一个函数。你应该叫它

if request.user.is_authenticated():
# do something if the user is authenticated

正如Peter Rowell指出的那样,在默认的Django模板语言中,调用函数时不使用圆括号。你可能在模板代码中看到过这样的东西:

{% if user.is_authenticated %}

然而,在Python代码中,它确实是User类中的一个方法。

以下模块应该工作:

    {% if user.is_authenticated %}
<p>Welcome \{\{ user.username }} !!!</p>
{% endif %}

Django 1.10 +

使用属性作为方法:

if request.user.is_authenticated: # <-  no parentheses any more!
# do something if the user is authenticated

同名方法的使用在Django 2.0中已被弃用,在Django文档中也不再提及。

人力资源> < p > < 注意,对于Django 1.10和1.11,该属性的值是CallableBool而不是布尔值,这可能会导致一些奇怪的错误。 例如,我有一个视图返回JSON

return HttpResponse(json.dumps({
"is_authenticated": request.user.is_authenticated()
}), content_type='application/json')

更新到属性request.user.is_authenticated后抛出异常TypeError: Object of type 'CallableBool' is not JSON serializable。解决方案是使用JsonResponse,它可以在序列化时正确处理CallableBool对象:

return JsonResponse({
"is_authenticated": request.user.is_authenticated
})

你认为:

{% if user.is_authenticated %}
<p>\{\{ user }}</p>
{% endif %}

在你的控制器函数中添加decorator:

from django.contrib.auth.decorators import login_required
@login_required
def privateFunction(request):

对于Django 2.0 +版本,使用:

    if request.auth:
# Only for authenticated users.

更多信息请访问https://www.django-rest-framework.org/api-guide/requests/#auth

request.user.is_authenticated()在Django 2.0+版本中被移除。

如果你想在你的模板中检查认证用户,那么:

{% if user.is_authenticated %}
<p>Authenticated user</p>
{% else %}
<!-- Do something which you want to do with unauthenticated user -->
{% endif %}

要在views.py文件中检查user是否已登录(已验证的用户),请使用"is_authenticated"方法,示例如下:

def login(request):
if request.user.is_authenticated:
print('yes the user is logged-in')
else:
print('no the user is not logged-in')

要检查用户是否登录(认证用户)在你的HTML模板文件中,你也可以使用它作为下面的例子:

 {% if user.is_authenticated %}
Welcome,\{\{request.user.first_name}}


{% endif %}

这只是一个示例,请根据您的需求进行更改。

我希望这对你有帮助。