'Django REST Framework ApiView not allowing DELETE

I am new to Django and I am having a issue sending a DELETE request to a class based view which inherits from APIView.

Here is my class:

class PageDetail(APIView):


    def get(self, request, pk):
        page = get_object_or_404(Page, pk=pk)
        data = PageSerializer(page).data
        return Response(data)

    def put(self, request, pk):

            stream = io.BytesIO(request.body)
            response = JSONParser().parse(stream)

            page = Page.objects.get(pk=pk)
            page.title = response.get('title', page.title)
            page.content = response.get('content', page.content)
            user = User.objects.get(pk=response.get('author', page.author))
            page.author = user
            page.save()

            return HttpResponseRedirect(reverse('pages_detail', args=(page.id,)))


    def delete(self, request, pk):
            page = Page.objects.get(pk=pk)
            page.delete()

            return HttpResponseRedirect(reverse('pages_list'))

When I make the DELETE request, the resource is deleted, but the page responds with the message:

{'detail':'Method 'DELETE' not allowed.'}

Although in the header I have:

Allow: GET, PUT, DELETE, HEAD, OPTIONS

Anyone have any ideas?



Solution 1:[1]

Using APIView you need to specify the http_method_names attribute explicitly.

Example:

class PageDetail(APIView):
    """
        page detail api view.
    """
    permission_classes = (
        permissions.IsAuthenticated,
    )
    http_method_names = [
        'delete',
        'head',
        'options',
    ]

    def delete(self, request, pk, *args, **kwargs):
        return Response(status=200)
        

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Qasim Khokhar