[Fixed]-Django REST Framework (ModelViewSet), 405 METHOD NOT ALLOWED

9👍

You don’t need router in you url mapping, unless you have a customized action other than the following:

    def list(self, request):
        pass

    def create(self, request):
        pass

    def retrieve(self, request, pk=None):
        pass

    def update(self, request, pk=None):
        pass

    def partial_update(self, request, pk=None):
        pass

    def destroy(self, request, pk=None):
        pass

add this to your views.py:

account_list = AccountViewSet.as_view({
    'get': 'list',
    'post': 'create'
})

in urls.py:

 url(r'^account/$', account_list, name='account-list'),
👤Dhia

2👍

The problem is with urls.py. Because url(r'^.*$'... comes before url(r'^api/v1/, Django simply discards the latter and routes the request to the IndexView.

0👍

For those who encounter similar error, sometimes it’s just that the order of the URLs evaluation is not good. In this example, if you put r"" first, r"status" cannot be found and will result in similar error like the OP.

from django.urls import include, path
from rest_framework import routers

from subscription.views import SubscriptionViewSet, SubscriptionStatusViewSet

router = routers.DefaultRouter()
router.register(r"status", SubscriptionStatusViewSet)
router.register(r"", SubscriptionViewSet)

urlpatterns = [path("", include(router.urls))]

You can read more about how Django URLs work here.

Leave a comment