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)
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)
- What is query.clone(), queryset.clone() for in django?
- Django admin β select reverse foreign key relationships (not create, I want to add available)
- Why does Django use tuples for settings and not lists?
- Django __call__() missing 1 required keyword-only argument: 'manager'
7π
Try django-cleanup, it automatically invokes delete method on FileField when you remove model.
- Does Django have a way to open a HTTP long poll connection?
- Validating a Django model field based on another field's value?
- What is the IP address of my heroku application
- Django Rest Framework: Serialize data from nested json fields to plain object
- Relation does not exist error in Django
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
- How can I disable a model field in a django form
- Get the version of Django for application
- Email as username in Django
- Django: serving ADMIN media files
- "The path python3 (from βpython=python3) does not exist" error