[Fixed]-How to convert request.user into a proxy auth.User class?

17👍

It’s another database hit, but this will work:

OrderedUser.objects.get(pk=request.user.pk)

Edit You could try:

o = OrderedUser()
o.__dict__ = request.user.__dict__

16👍

I couldn’t get the copy dict method to work on Python 2.7.4 and Django 1.6. I didn’t trace it all the way down, but I think it had something to do with it being a lazy object.

What worked for me:

request.user.__class__ = OrderedUser

It avoids the database call and gives access to the base auth stuff and all my extended behaviors.

To make the request.user act like the proxy class always, I put the assignment in middleware after the authentication middleware and before any of my apps could reference it. Since the middleware is called on every request, make sure the user is authenticated before setting the class. Using your example, here is how the middleware code might look:

from yourapp.models import OrderedUser

class OrderedUserMiddleware():
    def process_request(self, request):
        if hasattr(request, 'user') and request.user.is_authenticated():
            request.user.__class__ = OrderedUser

And remember to register the middleware after the authentication:

MIDDLEWARE_CLASSES = [
    # ...middleware from the guts of Django, none of your middle wares yet...
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    # ...more middleware from the guts of Django, none of your middlewares yet...
    'yourapp.middleware.OrderedUserMiddleware',
    # ...more middleware from you other middlewares...
]

Leave a comment