anoop
anoop

Reputation: 57

Django-AWS S3, unable to delete bucket objects

I have a Django project with MySQL storage and media objects (images) are being stored in AWS S3 simple storage.

Admin can upload images through admin panel and its being displayed in website too.

When admin delete objects , it gets deleted in MySQL but it's associated images persists in S3 bucket.

SETTINGS.PY

AWS_ACCESS_KEY_ID = ''
AWS_SECRET_ACCESS_KEY = ''
AWS_STORAGE_BUCKET_NAME = ''
AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.me-south-1.amazonaws.com"
AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'}
PUBLIC_MEDIA_LOCATION = 'media'
MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/'
DEFAULT_FILE_STORAGE = 'news.storage_backends.MediaStorage'

STORAGE_BACKENDS.PY

from storages.backends.s3boto3 import S3Boto3Storage
from django.conf import settings


class MediaStorage(S3Boto3Storage):
    location = 'media'
    default_acl = 'public-read'
    file_overwrite = False

I am user details as attached,

enter image description here

Upvotes: 0

Views: 281

Answers (2)

anoop
anoop

Reputation: 57

I have used django-cleanup app , its fairly easy to setup https://pypi.org/project/django-cleanup/

In older version of Django, when a model instance is deleted it would delete associated media files too but in latest versions its not.

The above app can be installed and add to the app list, later if a model instance edited or deleted it would do the same in AWS S3 storage too

Upvotes: 0

Marco
Marco

Reputation: 2844

As Luiz said, the files persist after deleting the object. I recommend to create a signal to delete the files after the object has been deleted:

@receiver(models.signals.post_delete, sender=YourModel)
def remove_image_file_from_s3_on_delete(sender, instance, **kwargs):
    instance.your_field_name.delete(save=False)

Upvotes: 3

Related Questions