Saul Salcedo
Saul Salcedo

Reputation: 79

How to delete file from the media folder?

I have this code that deletes all the files saved in a folder and the files in the database table:

def delete(request):
    folder = '../f2candon/andon/static/media/fileupload'
    for the_file in os.listdir(folder):
        file_path = os.path.join(folder, the_file)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
        except Exception as e:
            print(e)
    delet = Media.objects.all()
    delet.delete()
    return HttpResponseRedirect('/mediafile/')

But I must place another one where only one file is deleted, whether it is deleted by the id, to delete it from the database I do it this way:

def delete_media(request, id):
    delete_file = Media.objects.get(pk=id)
    delete_file.delete()
    return HttpResponseRedirect('/mediafile/')

Is there a way to delete the same file from the media folder that has just been deleted in the database? The same files are found in the database and in the folder.

Regards.

Upvotes: 0

Views: 265

Answers (1)

dirkgroten
dirkgroten

Reputation: 20692

You can write a signal handler for post_delete that takes care of deleting the files after the object in the database is deleted:

@receiver(post_delete, sender=Media)
def delete_associated_files(sender, instance, **kwargs):
    """Removes the media file from disk after deletion."""
    if instance.file:  # assuming the field name is "file"
        instance.file.delete(save=False) 

Upvotes: 1

Related Questions