Nepo Znat
Nepo Znat

Reputation: 3260

Add user profile to request.user

I have multiple User Types which I represent by user profiles in the form of a model:

I need access to the specific user profile on every request. To avoid executing an extra query every time I would like to add directly a select_related to the request.user object.

I couldn't find anything about it in the docs. Does anyone know the best way to do that?

Upvotes: 9

Views: 657

Answers (1)

mfrackowiak
mfrackowiak

Reputation: 1304

Interesting question. Looking at the source code of AuthenticationMiddleware and auth.get_user it seems that only thing you'll need to do will be to implement and use you own authentication backend. If you don't use any other custom backend features, you can subclass the ModelBackend, overriding only the get_user method to suit your needs:

class MyModelBackend(ModelBackend):
    def get_user(self, user_id):
        try:
            user = UserModel._default_manager.select_related("profile").get(pk=user_id)
        except UserModel.DoesNotExist:
            return None
        return user if self.user_can_authenticate(user) else None

Of course, you'll need to add it to your settings AUTHENTICATION_BACKENDS.

Upvotes: 12

Related Questions