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

request.user.is_authenticated

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

>

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

request.user.is_active

返回一个成功的响应。


当前回答

你认为:

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

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

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

其他回答

要在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 %}

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

我希望这对你有帮助。

你认为:

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

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

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

以下模块应该工作:

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

如果你想在你的模板中检查认证用户,那么:

{% if user.is_authenticated %}
    <p>Authenticated user</p>
{% else %}
    <!-- Do something which you want to do with unauthenticated user -->
{% endif %}

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