Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add user profile to request.user

Tags:

python

django

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

  • Student
  • Teacher

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?

like image 202
Nepo Znat Avatar asked Feb 21 '19 11:02

Nepo Znat


Video Answer


1 Answers

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.

like image 82
mfrackowiak Avatar answered Oct 12 '22 13:10

mfrackowiak