-1

How to jundge the request.user is AnonymousUser in Django?

class UserListAPIView(ListAPIView):
    serializer_class = UserSerializer
    permission_classes = []
    queryset = User.objects.all()

    def get(self, request):

        if request.user:
            print("not AnonymousUser" ) # there I tried

        return Response(data="200", status=HTTP_200_OK)

You see, I tried request.user to check the user whether exist, but failed, always print the not AnonymousUser. How to check it?

Exprator
  • 26,992
  • 6
  • 47
  • 59
1243916142
  • 365
  • 6
  • 17

1 Answers1

3

You should use the user's is_authenticated method to check a user whether login:

if request.user.is_authenticated():
    # Do something for logged-in users.
else:
    # Do something for anonymous users.

Thanks @Alasdair, after the Django v1.10 version, the is_authenticated is a attribute now. you can easy use request.user.is_authenticated to check it.

aircraft
  • 25,146
  • 28
  • 91
  • 166