代码之家  ›  专栏  ›  技术社区  ›  Rick

如何检查用户是否已登录(如何正确使用用户。是否经过验证)?

  •  208
  • Rick  · 技术社区  · 15 年前

    我正在看 this website 但似乎不知道该怎么做,因为它不起作用。我需要检查当前站点用户是否已登录(已验证),并尝试:

    request.user.is_authenticated
    

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

    >
    

    我可以执行其他请求(从上面URL的第一部分),例如:

    request.user.is_active
    

    返回成功的响应。

    5 回复  |  直到 7 年前
        1
  •  445
  •   Anupam ruddra    8 年前

    Django 1.10的更新+ : is_authenticated 现在是django 1.10中的属性。该方法仍然存在向后兼容性,但将在Django 2.0中删除。

    适用于Django 1.9及以上 :

    已通过身份验证 是一个函数。你应该这样称呼它

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

    正如彼得·罗威尔指出的那样,在默认的Django模板语言中,您可能会感到困惑,因为您不需要在括号中加上括号来调用函数。因此,您可能在模板代码中看到类似的情况:

    {% if user.is_authenticated %}
    

    但是,在Python代码中,它确实是 User 班级。

        2
  •  15
  •   Sopan    10 年前

    应使用以下块:

        {% if user.is_authenticated %}
            <p>Welcome {{ user.username }} !!!</p>       
        {% endif %}
    
        3
  •  15
  •   Mark Chackerian    8 年前

    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
    })
    
        4
  •  2
  •   Cubiczx    8 年前

    在你看来:

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

    在控制器函数中,添加decorator:

    from django.contrib.auth.decorators import login_required
    @login_required
    def privateFunction(request):
    
        5
  •  -2
  •   Jatin Goyal    7 年前

    为了 Django 2 + 版本使用:

        if request.auth:
           # Only for authenticated users.
    

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

    已在django 2.0+版本中删除request.user.is_authenticated()。