我正在查看这个网站,但似乎无法弄清楚如何实现,因为它没有起作用。我需要检查当前站点用户是否已登录(通过身份验证),并尝试使用以下方法:
request.user.is_authenticated
尽管确定用户已登录,它只返回:>
我能够执行其他请求(来自上面网址的第一部分),例如:
request.user.is_active
这会返回一个成功的响应。
我正在查看这个网站,但似乎无法弄清楚如何实现,因为它没有起作用。我需要检查当前站点用户是否已登录(通过身份验证),并尝试使用以下方法:
request.user.is_authenticated
尽管确定用户已登录,它只返回:>
我能够执行其他请求(来自上面网址的第一部分),例如:
request.user.is_active
这会返回一个成功的响应。
is_authenticated
是一个属性
if request.user.is_authenticated:
# do something if the user is authenticated
is_authenticated()
是一个函数。调用方式如下:
if request.user.is_authenticated():
# do something if the user is authenticated
{% if user.is_authenticated %}
User
类中的一个方法。Django 1.10+
使用属性而不是方法:
if request.user.is_authenticated: # <- no parentheses any more!
# do something if the user is authenticated
在Django 2.0中,同名方法的使用已被弃用,并且不再在Django文档中提及。
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
})
request.user
的。无论用户是否登录,只有在请求的上下文中才有影响,例如浏览器会话。 - Mark Chackerian以下代码块应该能正常工作:
{% if user.is_authenticated %}
<p>Welcome {{ user.username }} !!!</p>
{% endif %}
在您看来:
{% if user.is_authenticated %}
<p>{{ user }}</p>
{% endif %}
在您的控制器函数中添加装饰器:from django.contrib.auth.decorators import login_required
@login_required
def privateFunction(request):
request.user.is_authenticated
。 - Tony Suffolk 66如果您想在模板中检查经过身份验证的用户,请执行以下操作:
{% if user.is_authenticated %}
<p>Authenticated user</p>
{% else %}
<!-- Do something which you want to do with unauthenticated user -->
{% endif %}
在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 %}
这只是一个例子,根据您的需求进行更改。
我希望对您有所帮助。
对于 Django 2.0+ 版本,请使用:
if request.auth:
# Only for authenticated users.
更多信息请访问https://www.django-rest-framework.org/api-guide/requests/#auth
Django 2.0+版本中已删除request.user.is_authenticated()。