Django中如何检查用户是否匿名?
def index(request):
the_user = request.user
在Django中,我如何知道它是否是真实用户?我尝试过:
if the_user:
但即使没有人登录,“AnonymousUser”仍然存在。因此,它总是返回 true,这是行不通的。
def index(request):
the_user = request.user
In Django, how do I know if it's a real user or not? I tried:
if the_user:
but "AnonymousUser" is there even if no one logs in. So, it always returns true and this doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您可以检查是否
request.user.is_anonymous
返回True
。You can check if
request.user.is_anonymous
returnsTrue
.另一种方法
是通过测试来查看用户对象的 id 是什么:
请参阅 https ://docs.djangoproject.com/en/dev/ref/contrib/auth/#anonymous-users
An Alternative to
is by testing to see what the id of the user object is:
see https://docs.djangoproject.com/en/dev/ref/contrib/auth/#anonymous-users
您应该检查 的值
request.user.is_authenticated
。对于User
实例,它将返回True
;对于AnonymousUser
实例,它将返回False
。一个答案建议使用
is_anonymous
,但是django.contrib.auth 文档 说“你应该更喜欢使用is_authenticated
到is_anonymous
”。You should check the value of
request.user.is_authenticated
. It will returnTrue
for aUser
instance andFalse
for anAnonymousUser
instance.One answer suggests using
is_anonymous
but the django.contrib.auth documentation says “you should prefer usingis_authenticated
tois_anonymous
”.我遇到了类似的问题,只不过这是在 login_redirect_url 发送到的页面上。我必须输入模板:
I had a similar issue except this was on a page that the login_redirect_url was sent to. I had to put in the template:
我知道我在这里做了一些坟墓挖掘,但谷歌搜索将我带到了这个页面。
如果你的视图定义要求用户登录,你可以实现 @login_required 装饰器:
I know I'm doing a bit of grave digging here, but a Google search brought me to this page.
If your view def requires that the user is logged in, you can implement the @login_required decorator:
在 Django Rest 框架中,最好使用权限类来检查用户是否经过身份验证。这将适用于整个视图集。最简单的形式可能如下所示:
In Django rest framework it's good idea to use permission classes to check if user is authenticated. This will apply to whole viewSet. In the simpliest form it could look like this:
您应该使用
request.user.is_authenticated
因为它是request.user.is_anonymous
(接受的答案)You should use
request.user.is_authenticated
as it is the preferred solution over therequest.user.is_anonymous
(the accepted answer)您可以使用 is_authenticated< /a> 和 is_anonymous 与 HttpRequest.user< /a> 和 get_user(request) 到检查 Django 视图中的用户是否是匿名的,如下所示。 *文档 建议使用
is_authenticated
而不是is_anonymous
:并且,您可以在 Django 模板中检查用户是否是匿名的,如下所示:
You can use is_authenticated and is_anonymous with HttpRequest.user and get_user(request) to check if the user is anonymous or not in Django Views as shown below. *The doc recommends
is_authenticated
instead ofis_anonymous
:And, you can check if the user is anonymous or not in Django Templates as shown below: