django - get user logged into test client

Actually you can't access the current user via a test client response.

However, you can check if some user is logged in. Inspecting self.client.session will do:

self.client.session['_auth_user_id']
>>> 1

There is a more detailed answer for this.


The test client is request-agnostic. It doesn't inherently hold information about what users are logged in. (Neither does your actual webserver or the Django dev server, either, for obvious reasons, and those same reasons apply here).

login is simply a convenience method on the test client to essentially mimic a POST to /login/ with the defined user credentials. Nothing more.

The actual user is available on the request just like in a view. However, since you don't have direct access to the view, Django makes request available on the view's response. After you actually use the test client to load a view, you can store the result and then get the user via:

response.request.user

More recent versions of Django will use:

response.wsgi_request.user

I don't know which version you are using. Since 1.10.2, there is a wsgi_request attribute in response, it serves as request object in your view.

So It's very simple to get logged in user:

response.wsgi_request.user

Tags:

Testing

Django