@@ -264,6 +264,9 @@ def __init__(
264264
265265 super ().__init__ (verbose_name = verbose_name , name = name , ** kwargs )
266266
267+ # The attribute name of the old file to use on the model object
268+ self ._old_attname = "_old_%s" % name
269+
267270 def add_variation (self , name , params ):
268271 variation = self .def_variation .copy ()
269272 variation ["kwargs" ] = {}
@@ -313,9 +316,19 @@ def save_form_data(self, instance, data):
313316 if self .delete_orphans and (data is False or data is not None ):
314317 file = getattr (instance , self .name )
315318 if file and file ._committed and file != data :
316- file .delete (save = False )
319+ # Store the old file which should be deleted if the new one is valid
320+ setattr (instance , self ._old_attname , file )
317321 super ().save_form_data (instance , data )
318322
323+ def pre_save (self , model_instance , add ):
324+ if hasattr (model_instance , self ._old_attname ):
325+ # Delete the old file and its variations from the storage
326+ old_file = getattr (model_instance , self ._old_attname )
327+ old_file .delete_variations ()
328+ old_file .storage .delete (old_file .name )
329+ delattr (model_instance , self ._old_attname )
330+ return super ().pre_save (model_instance , add )
331+
319332 def deconstruct (self ):
320333 name , path , args , kwargs = super ().deconstruct ()
321334 return (
0 commit comments