Overwrite over a file and delete old model's object if the file exists
-
23-06-2021 - |
Question
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 2
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
OTHER TIPS
A few things to check before continuing to troubleshoot:
- Have you set the MEDIA_ROOT and MEDIA_URL in the settings.py file?
- Check this link for more info on Managing files
- I would take advantage of Django's built-in file storage rather than building something from scratch
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow