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

PythonDjangoDjango UsersDjango Contrib

Python Problem Overview


I have the following method:

def _attempt(actor):
    if actor.__class__ != User:
        raise TypeError

Which is called from a view:

self.object.attempt(self.request.user)

As you can see, the _attempt method expects actor to be type django.contrib.auth.models.User, however the object appears to be of type django.utils.functional.SimpleLazyObject. Why is this so? And more importantly, how can I convert the LazyObject (which apparently is a kind of wrapper for a User object) into a User object?

More info on Request.user is available here: https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.user This documentation seems to indicate the request.user should be a User object...

======Post-edit=====

I've got the following method now:

def _attempt(obj, action, actor, msg): 
    actor.is_authenticated() 
    if isinstance(actor, LazyObject): 
        print type(actor) 

I'm passing a user, however the if condition is still true, actor is still a LazyObject. Why is this so?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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!)

Solution 3 - Python

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.

Solution 4 - Python

For anyone wanting to write a failing "small" unittest for your code, you can generate a wrapped User and stuff it inside a request.

from django.contrib.auth import get_user_model
from django.test import RequestFactory
from django.utils.functional import SimpleLazyObject

user = get_user_model().objects.create_user(
    username='jacob',
    email='jacob@…',
    password='top_secret',
)

factory = RequestFactory()
request = factory.get('/')
request.user = SimpleLazyObject(lambda: user)

See:

Solution 5 - Python

This might be helpful to others and a bit cleaner.

The python method isinstance(instance, class) returns if the SimpleLazyObject's contained instance is of the provided class.

if isinstance(request.user, User):
    user = request.user

Solution 6 - Python

change your code like this and there should be no problem:

from copy import deepcopy

def _attempt(actor):
    actor = deepcopy(actor)
    if actor.__class__ != User:
        raise TypeError

Solution 7 - Python

This is the schema of the auth_user table in Django -

id
password
last_login
is_superuser
username
last_name
email
is_staff
is_active
date_joined
first_name

Now if you want id write like -

req.user.id

and if you want username write like -

req.user.username

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
QuestionHimerziView Question on Stackoverflow
Solution 1 - PythonChris PrattView Answer on Stackoverflow
Solution 2 - PythonUsAaR33View Answer on Stackoverflow
Solution 3 - PythonAndré StaltzView Answer on Stackoverflow
Solution 4 - PythonjamescView Answer on Stackoverflow
Solution 5 - PythonJames BrewerView Answer on Stackoverflow
Solution 6 - PythonMahdi SorkhmiriView Answer on Stackoverflow
Solution 7 - PythoncodingbruhView Answer on Stackoverflow