Python 如何检查此用户是匿名用户还是我系统上的实际用户?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4642596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:42:48  来源:igfitidea点击:

How do I check whether this user is anonymous or actually a user on my system?

pythondjangohttpauthentication

提问by TIMEX

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.

if the_user:但是即使没有人登录,“AnonymousUser”也在那里。因此,它总是返回 true 并且这不起作用。

采纳答案by Daniel DiPaolo

You can check if request.user.is_anonymousreturns True.

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

回答by leifos

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/#anonymous-users

回答by Karl M.W.

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:

如果你的视图定义需要用户登录,你可以实现@login_required 装饰器:

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    …

回答by Harlin

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_redirect_url 被发送到的页面上。我不得不放入模板:

{% if user.is_authenticated %}
    Welcome Back, {{ username }}
{% endif %}