Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a media file after each succesive upload in Django

My goal is that each time a user uploads a file to the media folder, that the previous file is deleted and replaced with the current. Essentially I only want a single file in the folder at a time. I have a working example that overwrites a file within the folder if it contains the same name and I figure that a simple modification to it would yield a solution, but I have't been able to correctly implement the modification.

The code I have to overwrite duplicates is as follows:

Models.py

class OverwriteStorage(FileSystemStorage):
    def get_available_name(self, name):
        if self.exists(name):
            os.remove(os.path.join(settings.MEDIA_ROOT, name))
        return name
class FileUpload(models.Model):
    docFile = models.FileField(upload_to='Data_Files', storage=OverwriteStorage(), blank=True)

    def __str__(self):
        return self.docfile.name

    @property
    def filename(self):
        return os.path.basename(self.docFile.name)

Any ideas on modifications or other potential solutions would be greatly appreciated.

like image 631
alacy Avatar asked Dec 05 '25 08:12

alacy


1 Answers

I managed to delete a media file easily using Django FileSystemStorage in Django==3.2. All you need to do is pass the absolute path of the file you want to delete into fs.delete(absolute_path) The absolute path can also be easily obtained from fs.path(filename)

from django.core.files.storage import FileSystemStorage

img_file = request.FILES['file']
fs = FileSystemStorage()
filename = fs.save(img_file.name, img_file)
uploaded_file_path = fs.path(filename)
""" 
   now that you have the absolute path
   you can just pass this to fs.delete(absolute_path) anytime
   to delete that particular media file like so,
"""
fs.delete(uploaded_file_path)
like image 73
because_im_batman Avatar answered Dec 07 '25 22:12

because_im_batman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!