I have a model:
class MyModel(models.Model):
...
def save(self):
print \"saving\"
...
def delete(self):
print \"deleting\"
Using django v2.2.2, I solved this problem with the following code
models.py
class MyModel(models.Model):
file = models.FileField(upload_to=)
def save(self, *args, **kwargs):
if self.pk is not None:
old_file = MyModel.objects.get(pk=self.pk).file
if old_file.path != self.file.path:
self.file.storage.delete(old_file.path)
return super(MyModel, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
ret = super(MyModel, self).delete(*args, **kwargs)
self.file.storage.delete(self.file.path)
return ret
admin.py
class MyModelAdmin(admin.ModelAdmin):
def delete_queryset(self, request, queryset):
for obj in queryset:
obj.delete()
For the DefaultAdminSite the delete_queryset is called if the user has the correct permissions, the only difference is that the original function calls queryset.delete()
which doesn't trigger the model delete
method. This is less efficient since is not a bulk operation anymore, but it keeps the filesystem clean =)