Home > Software engineering >  Difference between request.user vs. get_user(request) in Django?
Difference between request.user vs. get_user(request) in Django?

Time:09-19

I noticed there are two ways to get a user object from request (assuming user is already logged in and the session is valid):

  • user = request.user
  • user = get_user(request) where get_user() is imported from django.contrib.auth.

What's the difference? get_user() seems to do a lot of validation for request session.

Which is better?

CodePudding user response:

‍‍‍‍request.user is actually populated with get_user(request).

It happens in AuthenticationMiddleware:

request.user = SimpleLazyObject(lambda: get_user(request))

So when you get request.user, you are actually getting get_user(request) result.

  • Related