I have based my Django AWS S3 solution on https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html.
Now I am trying to find a way to delete a row in the model that contains the S3 file. I am able to delete the row with .delete()
but it doesn't delete the corresponding file in S3.
How do I make the deletion of the row also delete the corresponding file in S3 ? I'm using Django and django-storages.
Below is my code: (see edit history for more details):
https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py
https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py
https://gitlab.com/firdausmah/railercom/blob/master/railercom/settings.py (AWS settings)
https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/storage_backends.py
You have to explicitly delete the file. You could write a post delete signal or do it in the delete_employee
function.
employee.upload.delete(save=False) # delete file
employee.delete() # delete model instance
The docs for FileField.delete()
explains this.
Note that when a model is deleted, related files are not deleted. If you need to cleanup orphaned files, you’ll need to handle it yourself (for instance, with a custom management command that can be run manually or scheduled to run periodically via e.g. cron).
You should also make sure that there's no other FileField that references the exact same file before deleting it.