Where are request.user defined and assigned?

2 views
Skip to first unread message

Andy

unread,
May 10, 2011, 3:37:06 PM5/10/11
to Django users
I'm trying to understand how does request.user work.

Looking into the source code of the HttpRequest class (https://
code.djangoproject.com/browser/django/trunk/django/http/
__init__.py#L135) there is no "user" attribute for HttpRequest.

So where is the "user" attribute defined? And which code is
responsible to assign an User instance to that attribute?

Thanks

Shawn Milochik

unread,
May 10, 2011, 3:39:33 PM5/10/11
to django...@googlegroups.com
The User model is in django.contrib.auth, not in the core of Django.

request.user is dealt with in the middleware that comes with the auth
module.

http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/middleware.py


Andy

unread,
May 10, 2011, 4:00:38 PM5/10/11
to Django users
Thank you.

So LazyUser is there to cache the user instance.

In LazyUser(object), the user instance is stored in
request._cached_user

In AuthenticationMiddleware(object), the user instance is stored in
request.__class__.user

But I don't see request.user being assigned at all. Where does that
happen?

So what are the differences between the following three:
request._cached_user
request.__class__.user
request.user

Why have 3 different user attributes? I'm confused.

Thanks.
> http://code.djangoproject.com/browser/django/trunk/django/contrib/aut...

Shawn Milochik

unread,
May 10, 2011, 4:07:15 PM5/10/11
to django...@googlegroups.com
On 05/10/2011 04:00 PM, Andy wrote:
> Thank you.
>
> So LazyUser is there to cache the user instance.
>
Not exactly. It appears to be 'lazy' in that it doesn't actually do a
database lookup to get the user until it has to.
Read the LazyUser code and you'll see.

> In LazyUser(object), the user instance is stored in
> request._cached_user
>
> In AuthenticationMiddleware(object), the user instance is stored in
> request.__class__.user
>
> But I don't see request.user being assigned at all. Where does that
> happen?

In LazyUser, when it calls the get_user function. Using request.user in
your code will call __get__ on the LazyUser instance, and it'll actually
get the real User instance via the get_user function (unless it's
already cached, of course).

Shawn

Reply all
Reply to author
Forward
0 new messages