Ric*_*ick 225 python authentication django
我正在浏览这个网站,但似乎无法弄清楚如何做到这一点,因为它不起作用.我需要检查当前站点用户是否已登录(已通过身份验证),并且正在尝试:
request.user.is_authenticated
Run Code Online (Sandbox Code Playgroud)
尽管确定用户已登录,但它只返回:
>
Run Code Online (Sandbox Code Playgroud)
我可以做其他请求(来自上面网址的第一部分),例如:
request.user.is_active
Run Code Online (Sandbox Code Playgroud)
返回成功的响应.
Bri*_*eal 478
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
Run Code Online (Sandbox Code Playgroud)
正如Peter Rowell指出的那样,可能会让你失望的是,在默认的Django模板语言中,你没有使用括号来调用函数.所以你可能在模板代码中看到过这样的东西:
{% if user.is_authenticated %}
Run Code Online (Sandbox Code Playgroud)
但是,在Python代码中,它确实是User类中的一种方法.
Mar*_*ian 23
Django 1.10+
使用属性,而不是方法:
if request.user.is_authenticated: # <- no parentheses any more!
# do something if the user is authenticated
Run Code Online (Sandbox Code Playgroud)
在Django 2.0中不推荐使用同名方法,Django文档中不再提及.
CallableBool而不是布尔值,这可能会导致一些奇怪的错误.例如,我有一个返回JSON的视图
return HttpResponse(json.dumps({
"is_authenticated": request.user.is_authenticated()
}), content_type='application/json')
Run Code Online (Sandbox Code Playgroud)
更新到属性request.user.is_authenticated后抛出异常TypeError: Object of type 'CallableBool' is not JSON serializable.解决方案是使用JsonResponse,它可以在序列化时正确处理CallableBool对象:
return JsonResponse({
"is_authenticated": request.user.is_authenticated
})
Run Code Online (Sandbox Code Playgroud)
Sop*_*pan 17
以下块应该工作:
{% if user.is_authenticated %}
<p>Welcome {{ user.username }} !!!</p>
{% endif %}
Run Code Online (Sandbox Code Playgroud)
在您看来:
{% if user.is_authenticated %}
<p>{{ user }}</p>
{% endif %}
Run Code Online (Sandbox Code Playgroud)
在您的控制器函数中添加装饰器:
from django.contrib.auth.decorators import login_required
@login_required
def privateFunction(request):
Run Code Online (Sandbox Code Playgroud)
小智 6
如果您想在模板中检查经过身份验证的用户,则:
{% if user.is_authenticated %}
<p>Authenticated user</p>
{% else %}
<!-- Do something which you want to do with unauthenticated user -->
{% endif %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
201061 次 |
| 最近记录: |