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

request.user.is_authenticated

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

>

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

request.user.is_active

返回一个成功的响应。


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文档中也不再提及。

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

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

在更新到属性request.user之后。类型为“CallableBool”的对象不能被JSON序列化。解决方案是使用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 %}

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

我希望这对你有帮助。