You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django REST framework测试创建Post时遭遇403权限错误排查

Django REST Framework 创建Post测试用例遇403错误

编写创建新Post的测试用例时遇到403错误,执行py manage.py test命令后,第一个测试用例(查看帖子列表)正常通过,但第二个创建Post的测试返回403错误,打印response.data得到:

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

相关代码

urls.py

app_name = "blog_api"

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

permissions.py

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 == obj.author

views.py

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

tests.py

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(
            username="test_user",
            password="test_password",
        )
        data = {
            "title": "new",
            "author": 1,
            "excerpt": "new",
            "content": "new",
            "slug": "new",
        }
        url = reverse("blog_api:list_create")
        response = self.client.post(url, data, format="json")

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

settings.py

REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": [
        "rest_framework.permissions.IsAuthenticatedOrReadOnly",
    ],
}

已尝试操作

  • 注释PostDetail视图中的PostUserWritePermission权限类,仍出现相同错误
  • 在settings中添加TokenAuthentication,问题依旧

请问我遗漏了什么?

内容的提问来源于stack exchange,提问作者Vahid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 23:16:13