405 POST method not allowed

て烟熏妆下的殇ゞ 提交于 2019-11-27 21:49:28
Kevin Brown

This was resolved in the comments by user2663554

Problem solved, I miss one slash on the url.

This response code (405) can come from any number of issues, but it generally ends up that either you are using the wrong URL (as in this case), or you are using the wrong request method. Sometimes it's both!

Quite often I see people getting this issue when they are trying to update an individual resource (/api/res/1), but they are using the list url (/api/res) which doesn't allow the request to be made. This can also happen in the reverse, where someone is trying to create a new instance, but they are sending a POST request to the individual object.

In some cases, the wrong url is being used, so users are requesting a standard non-API view and thinking it is an API view (/res instead of /api/res). So make sure to always check your urls!

In my case i had a router with same base url

router.register('sales', SalesViewSet, basename='sales')

and my url patterns was

urlpatterns = [
    path('', include((router.urls, app_name))),
    path('sales/analytics/', Analytics.as_view(), name='create'),
]

I was getting 405 error for sales/analytics/. The solution was change the order of urlpatterns.

urlpatterns = [
    path('sales/analytics/', Analytics.as_view(), name='create'),
    path('', include((router.urls, app_name))),
]
class ApiIndexView(APIView)

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

class ApiIndexView(generics.ListCreateAPIView) 

there are many views in generic listcreateAPIview is used for get and post and createapiview is used only for post methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!