3

I'm trying to delete a Classroom object from the database. When I try to go to Django Rest Web Browser to fetch api/classroom/delete/1/ I get this response.

HTTP 405 Method Not Allowed
Allow: DELETE, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "detail": "Method \"GET\" not allowed."
}
class ClassroomDeleteViewAPI(generics.DestroyAPIView):
    serializer_class = ClassroomSerializer
    permission_classes = [IsAuthenticated]
    
    def get_queryset(self):
        return Classroom.objects.filter(teacher_assigned=self.request.user)
    
    def delete(self, request, pk):
        try:
            classroom = Classroom.objects.get(pk=pk)
            classroom.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        except Classroom.DoesNotExist:
            return Response({
                'detail': 'Classroom not found'
            }, status=status.HTTP_404_NOT_FOUND)

I don't know what happened here. There is no url route merging.

The View is correctly processing a delete request.

Why is that happening?

My path for delete looks like this:

path('classroom/delete/<int:pk>/', ClassroomDeleteViewAPI.as_view(), name='delete_classroom')

3 Answers 3

3

I think when opening the DRF web browser it always use get.

When I try to use curl -H some-token -X DELETE ``http://127.0.0.1:8000/api/classroom/delete/1/ it will actually delete

Sign up to request clarification or add additional context in comments.

1 Comment

Hello there Another option is to use proper API testing tools like POSTMAN. By default, the web browser makes a GET request if you open a link in the search/address bar or click a link.
1

Just an add-on to your question.
Here is something you can try.
Use Django's built-in destroy method.
Simplify your code by implementing DRF to handle the deletion.

class ClassroomDeleteViewAPI(generics.DestroyAPIView):
    serializer_class = ClassroomSerializer
    permission_classes = [IsAuthenticated]
    
    def get_queryset(self):
        return Classroom.objects.filter(teacher_assigned=self.request.user)

As said earlier, don't use the browser as it will make a GET request. REST API's are tied to specific HTTP methods.
I hope this helps.

Comments

1

The issue is that you're trying to access the DELETE endpoint using a GET request through the Django REST Web Browser. When you navigate to api/classroom/delete/1/ in your browser, it's making a GET request, but your view only accepts DELETE requests.

You can curl command:

curl -X DELETE http://your-domain/api/classroom/delete/1/ \
     -H "Authorization: Bearer your-token-here"

Or use a REST like Postman, Insomnia, or Thunder Client can make DELETE requests easily.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.