[Fixed]-Django – Delete file from amazon S3

32πŸ‘

βœ…

It is MUCH safer to do post_delete. If something goes wrong you will start missing S3 files and you wont notice it because your DB records are intact. post_delete will be safer since it is less likely that S3 delete operation would fail after you have deleted your db record. Furthermore even if file delete fails you will be left with a bunch of unreferenced S3 file which are harmless and can be easily cleaned up.

@receiver(models.signals.post_delete, sender=Picture)
def remove_file_from_s3(sender, instance, using, **kwargs):
    instance.img.delete(save=False)
πŸ‘€David Dehghan

11πŸ‘

You need to call FieldFile’s delete() method to remove the file in S3. In your case, add a pre_delete signal where you call it:

@receiver(models.signals.pre_delete, sender=ContentFile)
def remove_file_from_s3(sender, instance, using):
    instance.content.delete(save=False)
πŸ‘€tuomur

7πŸ‘

Try django-cleanup, it automatically invokes delete method on FileField when you remove model.

πŸ‘€un1t

0πŸ‘

This worked for me by deleting files both in DB and in AWS S3.

from django.db import models
from django.dispatch import receiver
from django.views import generic
from project.models import ContentFile
from django.contrib.auth.mixins import LoginRequiredMixin,UserPassesTestMixin

class DeleteFileView(LoginRequiredMixin,UserPassesTestMixin,generic.DeleteView):
   model = ContentFile
   template_name = 'file-delete.html'
   success_url = 'redirect-to'

   #Check if the owner of the file is the one trying to delete a file
   def test_func(self):
      obj = self.get_object()
      if obj.user == self.request.user:
        return True
      return False

    #This code does magic for S3 file deletion 
    @receiver(models.signals.pre_delete, sender=ContentFile)
    def remove_file_from_s3(sender, instance, using, **kwargs):
       instance.image_file.delete(save=False)

I am using pre_delete you can check the django documentation.File reference deletion in DB is done by DeleteView, I hope this helps someone

πŸ‘€sikaili99

Leave a comment