django’s self.client.force_login doesn’t work

I am using django 3.2 and self.client.force_login in test package doesn’t log in. this is the setUp method:

def setUp(self) -> None:
    self.user = User.objects.create_user(
        email='[email protected]',
        password='hiwa_asdf',
        name='smile as we go ahead'
    )
    self.client.force_login(self.user)

and here the test method:

def test_update_uer_profile(self):
    """testing if update user profile works"""

    data = {
        'name': 'Angry as hell',
        'password': 'hi there john'
    }
    response = self.client.patch(me_url, data)
    print(response.content)
    self.assertEqual(response.status_code, status.HTTP_200_OK)
    self.user.refresh_from_db()
    self.assertEqual(self.user.name, data['name'])
    self.assertTrue(self.user.check_password(data['password']))

and here’s the result:

Creating test database for alias 'default'...
System check identified no issues (0 silenced).
b'{"detail":"Authentication credentials were not provided."}'
F
======================================================================
FAIL: test_update_uer_profile (user.tests.test_user_api.PrivateApiTest)
testing if update user profile works
----------------------------------------------------------------------
Traceback (most recent call last):
  File "E:Programming_projectsDjangodrfrecipe_app_apiuserteststest_user_api.py", line 133, in test_update_uer_profile
    self.assertEqual(response.status_code, status.HTTP_200_OK)
AssertionError: 401 != 200

----------------------------------------------------------------------
Ran 1 test in 0.257s

FAILED (failures=1)
Destroying test database for alias 'default'...

Answer

Use force_authenticate(...) if you are using DRF

def setUp(self) -> None:
    self.user = User.objects.create_user(
        email='[email protected]',
        password='hiwa_asdf',
        name='smile as we go ahead'
    )
    self.client.force_authenticate(self.user)