Django REST framework: Getting 403 when trying to test create a new post

I'm trying to create a test for creating a new post, but I'm getting Error 403. I've read the questions on this topic, but either they were not about testing or the solution they provided did not work (I'll provide info about what I've tried so far).

Here is my code:

app_name = "blog_api"

urlpatterns = [
    path("<str:pk>/", PostDetail.as_view(), name="detail_create"),
    path("", PostList.as_view(), name="list_create"),

and my

class PostUserWritePermission(permissions.BasePermission):
    message = "Editing posts is restricted to the admin and author of the post only."

    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True
        return request.user.is_superuser or request.user ==

And here is my

class PostList(generics.ListCreateAPIView):
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    queryset = Post.post_objects.all()
    serializer_class = PostSerializer

class PostDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [PostUserWritePermission]
    queryset = Post.post_objects.all()
    serializer_class = PostSerializer

And finally, my

class PostTests(APITestCase):
    def test_view_posts(self):
        url = reverse("blog_api:list_create")
        response = self.client.get(url, format="json")
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_create_post(self):
        self.test_category = Category.objects.create(name="test category")
        self.test_user = User.objects.create_user(
        data = {
            "title": "new",
            "author": 1,
            "excerpt": "new",
            "content": "new",
            "slug": "new",
        url = reverse("blog_api:list_create")
        response =, data, format="json")

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

So, when I test using py test command, the first test is ok, but the second one returns error 403, and when I tried to see the response message using print( this is what's printed:

{'detail': ErrorDetail(string='Authentication credentials were not provided.', code='not_authenticated')}

I should also mention that I have this setting in my file:


I did some searching about this, this one question was a bit similar to my problem, but I create my user using create_user method, thus his solution is irrelevant to my question. What am I missing here?


I tried to comment out the permision class PostUserWritePermission in the PostDetail view, but got the same error nonetheless.

Also I tried to solve this by adding TokenAuthentication to my settings, but this didn't work neither.

Back to Top