我正在看这个网站,但似乎不知道如何做到这一点,因为它不工作。我需要检查当前站点用户是否已登录(已验证),并且正在尝试:
request.user.is_authenticated
尽管确定用户已经登录,但它只返回:
>
我能够做其他的请求(从url上面的第一部分),比如:
request.user.is_active
返回一个成功的响应。
我正在看这个网站,但似乎不知道如何做到这一点,因为它不工作。我需要检查当前站点用户是否已登录(已验证),并且正在尝试:
request.user.is_authenticated
尽管确定用户已经登录,但它只返回:
>
我能够做其他的请求(从url上面的第一部分),比如:
request.user.is_active
返回一个成功的响应。
当前回答
如果你想在你的模板中检查认证用户,那么:
{% if user.is_authenticated %}
<p>Authenticated user</p>
{% else %}
<!-- Do something which you want to do with unauthenticated user -->
{% endif %}
其他回答
以下模块应该工作:
{% 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 %}
要在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):
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类中的一个方法。