Opened 17 years ago

Closed 17 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: dev
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: no UI/UX: no

Description

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 )
    try:
        i = mod.objects.get(id=self.id)
    except:
        i = None
    else:
        for field in i._meta.fields:
            if field.get_internal_type() == 'FileField' or field.get_internal_type() == 'ImageField':
                if getattr(i,field.name) != getattr(self, field.name ):
                    path = getattr(i, 'get_%s_filename' % field.name)()
                    if os.path.isfile(path):
                        os.remove(path)
    super( mod, self ).save()

Change History (1)

comment:1 by Malcolm Tredinnick, 17 years ago

Resolution: wontfix
Status: newclosed

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