[Django]-Django Rest Framework doesn't return Response code from condition

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)

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()

Leave a comment