3

I'm trying to return a 405 response from DRF if the object is not allowed to be deleted, but I keep getting a Response 204_NO_CONTENT. Even though the instance is not deleted and the if statement works as should, the returned response is not correct. What am I doing wrong here?

Here's my code:

def perform_destroy(self, instance):
    if not instance.deletable:
        return Response({'error_message': 'Cannot delete last journal entry line.'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)
    sje_id = instance.journal_entry.id
    instance.delete()
    sje = PurchaseJournalEntry.objects.get(pk=sje_id)
    sje.regenerate_mutations()
    sje.save()

2 Answers 2

3

The perform_destroy [drf-doc] is not supposed to return a HTTP response. It simply is supposed to remove the object, not return a response. If you return a response, it is simply ignored.

You can override the destroy [drf-doc] function however, like:

def destroy(self, request, *args, **kwargs):
    instance = self.get_object()
    if not instance.deletable:
        return Response({'error_message': 'Cannot delete last journal entry line.'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)
    self.perform_destroy(instance)
    return Response(status=status.HTTP_204_NO_CONTENT)
Sign up to request clarification or add additional context in comments.

Comments

2

perform_destroy is not supposed to return anything.

If you want to alter this, either you should override the view's destroy or raise the proper exception:

from rest_framework.exceptions import MethodNotAllowed

def perform_destroy(self, instance):
    if not instance.deletable:
        raise MethodNotAllowed(default_detail='Cannot delete last journal entry line.')
    sje_id = instance.journal_entry.id
    instance.delete()
    sje = PurchaseJournalEntry.objects.get(pk=sje_id)
    sje.regenerate_mutations()
    sje.save()

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.