0

This might be a simple question, but I just thought I'd double check.

If I delete all of the objects in my django db that are linked to user uploaded media files, can I then manually delete everything in my media directory? I noticed when objects are deleted it does not delete the attached images, so since working on my project for months, there is a huge build up of images (most of which are duplicated). Is there a proper way to do this? Or will what I just described work?

On a side note, would switching to Amazon S3 be any better for these type of tasks?

stephan
  • 2,293
  • 4
  • 31
  • 55
  • Unfortunately the Django devs have rejected the idea of deleting objects once they are removed, even though the feature has been requested. There really is no better way that I am aware of than what you describe, and actually Amazon S3 will be worse for this because it is slower to delete everything. – Two-Bit Alchemist Feb 19 '15 at 22:31
  • @Two-BitAlchemist you get it wrong. In old versions of django db records and media files are deleted simultaneously, but it leads to broken data if transaction is failed. So this behaviour was changed to the current state - developer should take responsibility of deleting the files in the `delete()` method. – catavaran Feb 19 '15 at 22:44

2 Answers2

1

If you use django-extensions there is a management command to show you all files that are not linked to any object. You can try:

python manage.py unreferenced_files

If you want to delete these files you can use this command

python manage.py unreferenced_files | xargs -I{} rm -v {}

You can also make a cron job to periodically delete these files

If there is a folder in which you upload files and they are not linked to a model and you don't want to delete them (like if you use django-filebrowser) then you can pipe a grep with correct parameters before piping xargs

VStoykov
  • 1,705
  • 12
  • 15
0

Yes, you can manually delete media files for records deleted in the database.

Media files are not deleted automatically because of the transaction issues. For example you deleted the model and the image and then transaction is rolled back - deleted record will be "restored" to the db but image will be lost.

catavaran
  • 44,703
  • 8
  • 98
  • 85