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


Question

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.

1
60
1/9/2011 11:40:36 PM

Accepted Answer

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

101
7/30/2019 6:53:10 PM

An Alternative to

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

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

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon