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\":\
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')
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)]
You need to change just:
# views.py
class ApiIndexView(UpdateView):
permission_classes = (permissions.AllowAny,)
def post(self, request, format=None):
return Response("ok")
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