问题:如何检查用户是否已登录(如何正确使用user.is_authenticated)?
我正在看这个网站,但似乎无法弄清楚该怎么做,因为它不起作用。我需要检查当前站点用户是否已登录(已认证),并且正在尝试:
request.user.is_authenticated尽管确定用户已登录,但它仅返回:
>我能够执行其他请求(来自上述网址的第一部分),例如:
request.user.is_active这将返回成功的响应。
回答 0
Django 1.10+更新:is_authenticated现在是Django 1.10中的属性。为了向后兼容,该方法仍然存在,但在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类中的方法。
回答 1
Django 1.10+
使用属性,而不是方法:
if request.user.is_authenticated: # <-  no parentheses any more!
    # do something if the user is authenticatedDjango 2.0中已弃用了同名的方法,并且Django文档中不再提及。
请注意,对于Django 1.10和1.11,该属性的值是a
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
})回答 2
以下块应该工作:
    {% if user.is_authenticated %}
        <p>Welcome {{ user.username }} !!!</p>       
    {% endif %}回答 3
您认为:
{% if user.is_authenticated %}
<p>{{ user }}</p>
{% endif %}在控制器函数中添加装饰器:
from django.contrib.auth.decorators import login_required
@login_required
def privateFunction(request):回答 4
如果要在模板中检查经过身份验证的用户,则:
{% if user.is_authenticated %}
    <p>Authenticated user</p>
{% else %}
    <!-- Do something which you want to do with unauthenticated user -->
{% endif %}回答 5
对于Django 2.0+版本,请使用:
    if request.auth:
       # Only for authenticated users.有关更多信息,请访问https://www.django-rest-framework.org/api-guide/requests/#auth
在Django 2.0及更高版本中,request.user.is_authenticated()已被删除。

