Reputation: 163
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()
Upvotes: 3
Views: 1687
Reputation: 20976
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()
Upvotes: 2
Reputation: 476729
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)
Upvotes: 3