Deleting Django FileField files

March 3, 2011

I have a site that users upload files to. These files are releases, and as rows are deleted from the database, Django doesn't clear up the files. This script can be used from a cron job to delete files that are no longer needed.

Here's the model definition:

file = models.FileField(upload_to='DownloadFiles/%Y/%m/%d')

And here's the script that will look through all the rows of this model object, find all the files on disk in that directory, and list the ones that are not present in the database. This could obviously be extended to automatically delete the files, but I didn't want to go that far at this point.

import sys, os

sys.path = ['/home/path/to/application/'] + sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'app.settingsprod'

from app.downloads.models import DownloadFile

print "Files To Keep"
lFilesToKeep = []
lDownloadFiles = DownloadFile.objects.all().order_by('file')
for file in lDownloadFiles:
  lFilesToKeep.append(str(file))

print ""

print "Files on disk"
lRoot = "/home/location/of/media/root"
lDirectory = "DownloadFiles"
lYears = os.listdir("%s/%s" % (lRoot,lDirectory))
for year in lYears:
  lMonths = os.listdir("%s/%s/%s" % (lRoot, lDirectory, year))
  for month in lMonths:
    lDays = os.listdir("%s/%s/%s/%s" % (lRoot, lDirectory, year, month))
    for day in lDays:
      lFiles = os.listdir("%s/%s/%s/%s/%s" % (lRoot, lDirectory, year, month, day))
      for file in lFiles:
        lFilePath = "%s/%s/%s/%s/%s" % (lDirectory, year, month, day, file)
        if lFilePath in lFilesToKeep:
          print "KEEP   %s" % lFilePath
        else:
          print "DELETE %s" % lFilePath