[Solved]-Django APIClient login not working

8👍

First, {u'detail': u'Authentication credentials were not provided.'} occurs when the credential that you “provide” doesn’t match with models. (I think it is bad error message)

So, you should set user’s password by set_password() method, because of encryption.

self.user = CustomUser.objects.create_user(email="user1@test.com", is_staff=True)
self.user.set_password("password1")
self.user.save()

or, you can use force_login() for testing.

self.client.force_login(
    user=User.objects.first(),
    backend='django.contrib.auth.backends.ModelBackend' # one of your AUTHENTICATION_BACKENDS
)

4👍

You may need to use force_authenticate() method for logging in,

def test_add_name(self):
    self.client.force_authenticate(self.user)        
    ........

You may consider re-writing your test-case, maybe somewhat like this,

class AccountTests(APITestCase):

    def setUp(self):
        self.user = CustomUser.objects.create_user(email="user1@test.com", password="password1", is_staff=True)
        self.client = APIClient()

    def test_add_name(self):
        self.client.force_authenticate(self.user)

        url = reverse('customuser-detail', args=(self.user.id,))
        data = {'first_name': 'test', 'last_name': 'user'}
        response = self.client.put(url, data, format='json')

        self.assertEqual(response.status_code, status.HTTP_200_OK)

Leave a comment