I'm trying to test POSTing data to a view in django-rest-framework that requires authentication. But I can't. I've read many threads of supposed solutions, but can't find any that solves to me.
Test:
class TodoListCreateAPIViewTestCase(APITestCase): url = reverse("todolist:add") def setUp(self): self.username = "john" self.email = "[email protected]" self.password = "you_know_nothing" self.user = User.objects.create_user(self.username, self.email, self.password) self.token = Token.objects.create(user=self.user) #checking token here def test_create_todo(self): self.client.login(email=self.email, password='you_know_nothing') client = APIClient() client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) response = self.client.post(self.url, {"list_name": "Clean the room!"}, format='json') self.assertEqual(201, response.status_code) View
class Addtodolist(APIView): authentication_classes = (JSONWebTokenAuthentication,TokenAuthentication) permission_classes = [IsAuthenticated, ] def post(self, request): data = request.data todolist_instance = Todolist.objects.filter(for_user=self.request.user).first() if not todolist_instance: list_serilaizer = AddtodolistSerializers(data=data, context={'user': request.user}) if list_serilaizer.is_valid(): list_serilaizer.save() return Response(data=success_response(data=list_serilaizer.data, msg='Successfully Created list!'), status=status.HTTP_200_OK) else: return Response( failure_response(data={'detail': list_serilaizer.errors()}, msg='Following errors occured'), status=status.HTTP_400_BAD_REQUEST) else: return Response( failure_response(data={'detail': 'User can have only 1 List'}, msg='User can have only 1 List'), status=status.HTTP_409_CONFLICT)
client.post(...)instead ofself.client.post(...)