我如何检查这个用户是匿名的还是我系统上的用户?

时间:2021-04-29 12:58:23
def index(request):
    the_user = request.user

In Django, how do I know if it's a real user or not? I tried:

在Django中,我如何知道它是否是一个真正的用户?我试着:

if the_user: but "AnonymousUser" is there even if no one logs in. So, it always returns true and this doesn't work.

如果是the_user:但是“signatoususer”,即使没有人登录。所以,它总是返回true,而这不起作用。

3 个解决方案

#1


68  

You can check if request.user.is_anonymous returns True.

您可以检查request.user。is_anonymous返回True。

#2


12  

An Alternative to

另一种选择

if user.is_anonymous():
    # user is anon user

is by testing to see what the id of the user object is:

通过测试查看用户对象的id是什么:

if user.id == None:
    # user is anon user
else:
    # user is a real user

see https://docs.djangoproject.com/en/dev/ref/contrib/auth/#anonymous-users

看到https://docs.djangoproject.com/en/dev/ref/contrib/auth/匿名用户

#3


3  

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:

如果您的视图def要求用户登录,您可以实现@login_required decorator:

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    …

#1


68  

You can check if request.user.is_anonymous returns True.

您可以检查request.user。is_anonymous返回True。

#2


12  

An Alternative to

另一种选择

if user.is_anonymous():
    # user is anon user

is by testing to see what the id of the user object is:

通过测试查看用户对象的id是什么:

if user.id == None:
    # user is anon user
else:
    # user is a real user

see https://docs.djangoproject.com/en/dev/ref/contrib/auth/#anonymous-users

看到https://docs.djangoproject.com/en/dev/ref/contrib/auth/匿名用户

#3


3  

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:

如果您的视图def要求用户登录,您可以实现@login_required decorator:

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    …