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


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


Edit You could try:

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


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 from the guts of Django, none of your middle wares yet...
    # ...more middleware from the guts of Django, none of your middlewares yet...
    # ...more middleware from you other middlewares...

Leave a comment