gpt4 book ai didi

python - Django REST 框架中的 405 "Method POST is not allowed"

转载 作者:太空狗 更新时间:2023-10-29 17:49:46 24 4
gpt4 key购买 nike

我是 Django REST 框架的新手。如果我向 '/api/index/' 发出 POST 请求,有人可以解释为什么我会收到这样的错误

405 Method Not Allowed
{"detail":"Method \"POST\" not allowed."}

我的代码如下:

# views.py
class ApiIndexView(APIView):
permission_classes = (permissions.AllowAny,)

def post(self, request, format=None):
return Response("ok")

# urls.py
urlpatterns = [
url(r'^api/index/$', views.ApiIndexView.as_view()),
]

# settings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.DjangoModelPermissions',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
)
}

但如果我添加 <pk>进入我的模式,一切正常:

# views.py
class ApiIndexView(APIView):
permission_classes = (permissions.AllowAny,)

def post(self, request, pk, format=None):
return Response("ok")

# urls.py
urlpatterns = [
url(r'^api/index/(?P<pk>\d+)/$', views.ApiIndexView.as_view()),
]

我完全糊涂了。为什么有必要使用 <pk>有没有办法避免在 URL 模式中使用此参数?

最佳答案

确保您在http_method_names 中有"POST"。或者,您可以这样写:

def allowed_methods(self):
"""
Return the list of allowed HTTP methods, uppercased.
"""
self.http_method_names.append("post")
return [method.upper() for method in self.http_method_names
if hasattr(self, method)]

关于python - Django REST 框架中的 405 "Method POST is not allowed",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36011333/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com