Django/DRF - 405 Method not allowed on DELETE operation

◇◆丶佛笑我妖孽 提交于 2019-12-12 07:25:16

问题


I'm working with two dev servers on my local machine (node & django's).

I've added django-cors-headers to the project to allow all origins & methods (on dev) with the following settings :

CORS_ORIGIN_ALLOW_ALL = 'ALL'
CORS_ALLOW_METHODS = (
        'GET',
        'POST',
        'PUT',
        'PATCH',
        'DELETE',
        'OPTIONS'
    )

I'm getting 405 when attempting DELETE. Looking at the response headers

HTTP/1.0 405 METHOD NOT ALLOWED
Date: Mon, 03 Nov 2014 10:04:43 GMT
Server: WSGIServer/0.1 Python/2.7.5
Vary: Cookie
X-Frame-Options: SAMEORIGIN
Content-Type: application/json
Access-Control-Allow-Origin: *
Allow: GET, POST, HEAD, OPTIONS

Notice that DELETE & PATCH / PUT are not present in the allowed methods list.

Is there something missing from my configuration ?


回答1:


The response looks very similar to that of the list view (/api/resource/) for a ViewSet. List views only support GET, to list all of the objects, and POST to create a new object.

DELETE requests are only allowed on the detail view (/api/resource/1/). This is because Django REST Framework needs to know what object you are looking to delete, and this information cannot be retrieved from just the list view.




回答2:


If you need to connect http method DELETE with URL without pk in DRF try this inside of your ModelViewSet:

@action(methods=['delete'], detail=False)
def delete(self, request):
    # your code

UPD: Note that action attribute inside of ModelViewSet class will be None due request. If you check it somewhere, handle not only action name, but request method and request path.



来源:https://stackoverflow.com/questions/26711975/django-drf-405-method-not-allowed-on-delete-operation

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