Answers:
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类中的方法。
Django 1.10+
使用属性,而不是方法:
if request.user.is_authenticated: # <- no parentheses any more!
# do something if the user is authenticated
Django 2.0中已弃用了同名的方法,并且Django文档中不再提及。
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
})
request.user。用户是否登录仅取决于请求的上下文,例如浏览器会话。
以下块应该工作:
{% if user.is_authenticated %}
<p>Welcome {{ user.username }} !!!</p>
{% endif %}
您认为:
{% if user.is_authenticated %}
<p>{{ user }}</p>
{% endif %}
在控制器函数中添加装饰器:
from django.contrib.auth.decorators import login_required
@login_required
def privateFunction(request):
request.user.is_authenticated,如果你知道你的应用程序将始终注销用户
对于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()已被删除。
request.user.is_authenticated仍然有效。您引用的是django-rest-framework文档,而不是django