Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - update a model won't delete the old FileField

I am implementing an application with django, which has a model with a FileField:

class Slideshow(models.Model):
    name = models.CharField(max_length=30,unique=True)
    thumbnail = models.FileField(max_length=1000,upload_to="images/app/slideshows/thumbnails")

and I have an admin backend where django manages the models. I just added the file admin.py and django manages everything for me

from django.contrib import admin

from apps.gallery.models import Slideshow

admin.site.register(Slideshow)

In the backend, it is possible to add, delete and update the slideshows. However, when I try to update a slideshow and change its attribute thumbnail [FileField], django does not delete the old file. Consequently, after several updates the server is filled with many files which are useless. My question is: how can I make django delete those files automatically after an update?

I would really appreciate your help

like image 917
Raul San N.H. Avatar asked Jan 07 '10 22:01

Raul San N.H.


2 Answers

I thought much about this problem, and eventually I find out a solution than works well for me. You can find all models in project and connect pre_save and post_delete signals to them.

At the end I made app, which sloves this problem - django-cleanup

like image 162
un1t Avatar answered Oct 30 '22 19:10

un1t


I'm sure Django does this by design. It can't know, for example, whether any other models might be using that file. You would also be really surprised if you expected the file to remain and discovered that django deleted it!

However, there's also the issue that as soon as you change the file field, you lose the old file name.

There's an open ticket about that problem: http://code.djangoproject.com/ticket/11663

There's a patch in http://code.djangoproject.com/ticket/2983 which shows how to override __set__ to store the previous file name. Then your model's __save__ method can get access to the previous file name to delete it.

like image 35
Seth Avatar answered Oct 30 '22 19:10

Seth