Delete method on Django Rest Framework ModelViewSet

后端 未结 2 1625
北荒
北荒 2021-02-05 17:20

i have tried to delete a single ManuscriptItem instance using Postman to perform my API requests on against the view below:

class ManuscriptViewSet(viewsets.Mode         


        
相关标签:
2条回答
  • 2021-02-05 17:55
    def destroy(self, request, *args, **kwargs):
            try:
                instance = self.get_object()
                self.perform_destroy(instance)
            except Http404:
                pass
            return Response(status=status.HTTP_204_NO_CONTENT)
    

    use this and it will work

    0 讨论(0)
  • 2021-02-05 18:18

    The issue here is that you send DELETE request to the wrong url. Look at the DefaultRouter docs. It generates automatically your urls within your viewset:

    Look closely at the DELETE method. It is on the {prefix}/{lookup}/[.format] url pattern. This means that your corresponding router url is manuscripts/<manuscript_id>/, but you try to send DELETE request to manuscripts/ only, which is the above pattern. You see directly from the table that the allowed HTTP methods there are GET and POST only. That's why you receive MethodNotAllowed.

    The solution to your problem is not to pass the manuscript_id as a JSON body of the request

    {
        "manuscript": 7,
    }
    

    But to pass it directly to the url:

    DELETE http://localhost:8000/manuscripts-api/manuscripts/7/

    And you just register your viewset like:

    router.register(r'manuscripts', ManuscriptViewSet.as_view(), name='manuscripts')
    

    As you see, DRF generates the urls automatically for you.

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