request.user returns a SimpleLazyObject, how do I "wake" it?

See my answer on a similar question.

Django lazy loads request.user so that it can be either User or AnonymousUser depending on the authentication state. It only "wakes up" and returns the appropriate class when an attribute is accessed on it. Unfortunately, __class__ doesn't count because that's a primitive class attribute. There's occasions where you might need to know that this is actually a SimpleLazyObject type, and therefore it would be wrong to proxy it on to User or AnonymousUser.

Long and short, you simply can't do this comparison as you have it. But, what are you really trying to achieve here? If you're trying to check if it's a User or AnonymousUser, there's request.user.is_authenticated() for that, for example.

As a general rule though, you shouldn't abuse duck typing. A parameter should always be a particularly type or subtype (User or UserSubClass), even though it doesn't have to be. Otherwise, you end up with confusing and brittle code.


This should do it:

# handle django 1.4 pickling bug
if hasattr(user, '_wrapped') and hasattr(user, '_setup'):
    if user._wrapped.__class__ == object:
        user._setup()
    user = user._wrapped

I had to write this so I could add a user to the session dictionary. (SimpleLazyObjects are not picklable!)


user= request.user._wrapped if hasattr(request.user,'_wrapped') else request.user

Then you use user instead of request.user.

This is similar to UsAaR33's answer, but a one-liner is nicer for converting the object.