0
I would do something like this:
def perform_destroy(self, conversation):
if conversation.messages.exists():
return Response({'status': 'conversation has messages'}, status=status.HTTP_400_BAD_REQUEST)
else:
conversation.delete()
But to your question, I would say that if objects are being deleted when cantDelete() is True then they are not being deleted by that delete function.
1
According to this post https://stackoverflow.com/a/37308092/2073793
a better pattern would be:
class View(generics.RetrieveUpdateDestroyAPIView):
...
def destroy(self, request, *args, **kwargs):
if cantDelete():
return JsonResponse({ 'success' : False, 'message': "Can't delete this"}, status = 403)
self.perform_destroy(self.get_object())
return JsonResponse({ 'success' : True, 'message': "Deleted"})
That is, override the destroy method (not the delete method), and then call perform_destroy() rather than the object’s delete() method to actually delete the object if it’s allowed.
But I still don’t know whether the original code is problematic or not.
- How to put live video from web camera to Django website?
- Submitting all forms on a page with JavaScript using ajax at once to Django
- Best practice to handle different group of users accessing their own content
- Get logged in users details and group permissions in rest api
- Convert to Excel with Django
0
You could call .perform_destroy
if the can_delete
is True
class ConditionalDestroyMixin(object):
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
can_delete = instance.can_delete()
if can_delete:
self.perform_destroy(instance)
return Response(status=status.HTTP_204_NO_CONTENT)
msg = _(f'Unable to delete {instance}.')
data = {'detail': six.text_type(msg)}
return Response(data, status=status.HTTP_403_FORBIDDEN)
Source:stackexchange.com