[Django]-Django – get user logged into test client

57👍

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

42👍

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.

👤hso

13👍

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

10👍

You can log in with a test user like so:

from django.contrib.auth.models import User
user = User.objects.create_user('foo', 'myemail@test.com', 'bar')
self.client.login(username='foo', password='bar')

Now, you can just use user in your tests:

self.assertEqual(created_model_object.user, user)

Leave a comment