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

PythonDjangoHttpAuthentication

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

Solution 3 - Python

You should check the value of request.user.is_authenticated. It will return True for a User instance and False for an AnonymousUser instance.

One answer suggests using is_anonymous but the django.contrib.auth documentation says “you should prefer using is_authenticated to is_anonymous”.

Solution 4 - Python

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:

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    …

Solution 5 - Python

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:

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

Solution 6 - Python

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:

from rest_framework.permissions import IsAuthenticated
...
class SomeViewSet(viewsets.GenericViewSet):
    permission_classes = [IsAuthenticated]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTIMEXView Question on Stackoverflow
Solution 1 - PythonDaniel DiPaoloView Answer on Stackoverflow
Solution 2 - PythonleifosView Answer on Stackoverflow
Solution 3 - PythonJeff BowenView Answer on Stackoverflow
Solution 4 - PythonKarl M.W.View Answer on Stackoverflow
Solution 5 - PythonHarlinView Answer on Stackoverflow
Solution 6 - PythonTCFDSView Answer on Stackoverflow