+
+class OverwritingFieldFile(FieldFile):
+ """
+ Deletes the old file before saving the new one.
+ """
+
+ def save(self, name, content, *args, **kwargs):
+ leave = kwargs.pop('leave', None)
+ # delete if there's a file already and there's a new one coming
+ if not leave and self and (not hasattr(content, 'path') or
+ content.path != self.path):
+ self.delete(save=False)
+ return super(OverwritingFieldFile, self).save(
+ name, content, *args, **kwargs)
+
+
+class OverwritingFileField(models.FileField):
+ attr_class = OverwritingFieldFile
+
+