[Answered ]-Django test unit logged in user

1👍

The client API allows you to login a user like so:

self.client.force_login(user)

Just run that before accessing the profile page in your test.

There also is an error in your code.

...
self.user_id = UserProfile.objects.get(user=user)
...

Here you are assigning the profile object to user_id and later trying to pass user_id as parameter in the request, instead of the user ID. I am guessing that is why you get the error.

I would suggest to only set the user as object property; you do not need anything else. Then access it with self.user.id in your test.

See also: https://docs.djangoproject.com/en/4.0/topics/testing/tools/#django.test.Client.force_login

Leave a comment