'AnonymousUser' object is not iterable

帅比萌擦擦* 提交于 2020-03-18 03:48:15

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/37448624/anonymoususer-object-is-not-iterable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!