12
if not request.user.is_authenticated:
    return None

try:
    return ClientProfile.objects.get(user=request.user)
except ClientProfile.DoesNotExist:
    return None

This code should return None, if I'm not logged in and trying to call it. But as I see from stacktrace, it crashes with error "'AnonymousUser' object is not iterable" on this line:

return ClientProfile.objects.get(user=request.user)

I'm browsing the following page in private mode, so I'm 100% not authenticated.

How to fix this issue?

artem
  • 16,382
  • 34
  • 113
  • 189

3 Answers3

20

In Django 1.9 and earlier, is_authenticated() is a method, you must call it.

if not request.user.is_authenticated():
    ...

It's an easy mistake to forget to call the method. In your case it's causing an error, but in other cases it might allow users to have access to data that they shouldn't. From Django 1.10, is_authenticated is changing to a property to prevent this.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
1

This error might arise if you are trying to logging in as a guest user. In my project i m trying to provide membership on the basis of free,enterprise and professional and i got the same error.

so replace

return ClientProfile.objects.get(user=request.user) with

return ClientProfile.objects.filter().first()

0

I use another approach

from django.contrib.auth.models import AnonymousUser

user = request.user if type(request.user) is not AnonymousUser else None
try:
    ClientProfile.objects.get(user=user)
except ClientProfile.DoesNotExist:
    pass
Emmanuel Mtali
  • 4,383
  • 3
  • 27
  • 53