In a written django test, how can I get the current logged in user?
For example this is the test I want to write:
def test_author_set_once(self):
self.client.login(username='Adam', password='password')
#create an object and test the author is adam
self.client.login(username='Barry', password='password')
#modify the first object and test that the author has not changed
So I want to be able to say something like…
self.assertEqual(object.author, self.client.user)
(but I can’t)
The way I’ve coded it at the moment is like this:
self.client.login(username='Adam', password='password')
self.user = User.objects.get(username='Adam')
#create an object
self.assertEqual(object.author, self.user)
This relies on the assumption that the request.user is the same as a particular user object. I guess it’s OK but it seems a bit clunky.
Is there anyway to avoid the assumption?
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).
loginis 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
requestjust like in a view. However, since you don’t have direct access to the view, Django makesrequestavailable 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:More recent versions of Django will use: