Search code examples
djangodjango-file-upload

Overwrite over a file and delete old model's object if the file exists


I have made something to overwrite a file already uploaded with :

class OverwriteStorage(FileSystemStorage):
def get_available_name(self, name):
    if self.exists(name):
        os.remove(os.path.join(settings.MEDIA_ROOT, name))
    return name

But my file is in a model :

class Work (models.Model):
    file = models.FileField(storage=OverwriteStorage(), upload_to=path)
    group = models.ForeignKey(Group, related_name='work_list')

And the new upload makes a new enter, so I have :

  • A model without file (that bug when I ask file.size..)

  • My new model

How can I remove my model when my file is deleted?

I have tried to change again FileSystemStorage process but I can't use any argument (said in doc and tested for hours ;)), I have tried to change save process too, but I didn't succeed..


Solution

  • My solution :

    for work in groupwork : #It is the list of work associate with my group
        try :
           path = work.file.path.lstrip(SITE_ROOT+'/'+MEDIA_ROOT+'/').rstrip(request.FILES['file'].name)
           deletedwork = groupwork.get(file=path+request.FILES['file'].name)
           deletedwork.delete()
        except:
           pass