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

时间:2010-09-05 03:30:05

标签: python django authentication

我正在查看this website,但似乎无法弄清楚如何执行此操作,因为它不起作用。我需要检查当前站点用户是否已登录(已验证),并且正在尝试:

request.user.is_authenticated

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

>

我可以做其他请求(来自上面网址的第一部分),例如:

request.user.is_active

返回成功的回复。

7 个答案:

答案 0 :(得分:449)

更新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 :(得分:17)

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.is_authenticated后,抛出异常TypeError: Object of type 'CallableBool' is not JSON serializable。解决方案是使用JsonResponse,它可以在序列化时正确处理CallableBool对象:

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

答案 2 :(得分:15)

以下块应该有效:

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

答案 3 :(得分:2)

在您看来:

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

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

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

答案 4 :(得分:1)

如果要在模板中检查经过身份验证的用户,则:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val viewModel = ViewModelProvider(this).get(TestVM::class.java)
}

答案 5 :(得分:0)

在views.py文件中检查用户是否登录(认证用户),使用“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 %}

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

希望对你有帮助。

答案 6 :(得分:-2)

对于 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+版本中删除。

相关问题