405 “Method POST is not allowed” in Django REST framework

前端 未结 4 1884
暖寄归人
暖寄归人 2021-01-04 07:15

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\":\         


        
相关标签:
4条回答
  • 2021-01-04 07:48

    Your own comment is right. You just included the index url before. And that main view recieve url parameter for retreiving objects, so your new view is interpreted as param. I had the same problem in urls.py:

    router = DefaultRouter()
    router.register(r'', views.MainViewSet, basename='index')
    router.register(r'other_view', views.OtherViewSet, basename='typeservice')
    

    Solution:

    router = DefaultRouter()
    router.register(r'main', views.MainViewSet, basename='index')
    router.register(r'other_view', views.OtherViewSet, basename='other_view')
    
    0 讨论(0)
  • 2021-01-04 07:50

    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)]
    
    0 讨论(0)
  • 2021-01-04 07:50

    You need to change just:

    # views.py
    class ApiIndexView(UpdateView):
        permission_classes = (permissions.AllowAny,)
    
        def post(self, request, format=None):
            return Response("ok")
    
    0 讨论(0)
  • 2021-01-04 07:54
    class ApiIndexView(APIView) 
    

    instead of this please import from rest_framework import generics and change it to

    class ApiIndexView(generics.ListCreateAPIView) 
    

    There are many generic views. ListCreateAPIView is used for GET and POST and CreateAPIView is used only for POST methods

    0 讨论(0)
提交回复
热议问题