405“不允许方法开机自检”。在Django REST框架中 [英] 405 "Method POST is not allowed" in Django REST framework

查看:91
本文介绍了405“不允许方法开机自检”。在Django REST框架中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new in Django REST framework. Can someone explain why I get such error, if I make a POST request to '/api/index/'

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> 我在我的模式中,一切正常:

But if I add <pk> into my pattern, everything works fine:

# 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模式中使用此参数?

I am completely confused. Why it's necessary to use <pk> and is there a way to avoid the use of this parameter in the URL pattern?

推荐答案

请确保您在 http_method_names 中具有 POST 。另外,您也可以这样写:

Make sure that you have "POST" in http_method_names. Alternatively, you can write it like this:

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)]

这篇关于405“不允许方法开机自检”。在Django REST框架中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆