Add user profile to request.user

  • A+
Category:Languages

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?

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: