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.
- [Django]-Django-rest-framework how to make model serializer fields required
- [Django]-Django Celery – Cannot connect to amqp://guest@127.0.0.8000:5672//
- [Django]-How to automatically destroy django test database
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
- [Django]-How do you detect a new instance of the model in Django's model.save()
- [Django]-How to limit columns returned by Django query?
- [Django]-Django: Get an object form the DB, or 'None' if nothing matches
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)
- [Django]-How to show a PDF file in a Django view?
- [Django]-Django post_save() signal implementation
- [Django]-Prompt file download with XMLHttpRequest