Opened 9 years ago

Closed 9 years ago

#6157 closed (wontfix)

Code to delete files when updating a filefield

Reported by: aribao@… Owned by: nobody
Component: Database layer (models, ORM) Version: master
Severity: Keywords: delete file update
Cc: aribao@… Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:


I'm using this code in my custom the save() methods. It looks for a filefield or imagefield, and delete the previous file when you insert a new one. Perhaps it could be a good idea to include it by defauly inside the save method of the object.

from django.db.models import get_model
import os
def save(self):
    mod = get_model( self._meta.app_label, self._meta.object_name )
        i = mod.objects.get(
        i = None
        for field in i._meta.fields:
            if field.get_internal_type() == 'FileField' or field.get_internal_type() == 'ImageField':
                if getattr(i, != getattr(self, ):
                    path = getattr(i, 'get_%s_filename' %
                    if os.path.isfile(path):
    super( mod, self ).save()

Change History (1)

comment:1 Changed 9 years ago by mtredinnick

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to wontfix
  • Status changed from new to closed

Deleting files automatically when saving is very dangerous behaviour (what if something outside Django is using the file?), so this would always have to be customisable. Also, there is a general ongoing discussion about rewriting the file saving backends and this issue is being covered as part of that. So I don't think this change is worth committing as is at the moment.

Note: See TracTickets for help on using tickets.
Back to Top