简体   繁体   English

如何从媒体文件夹中删除文件?

[英]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:但是我必须放置另一个只删除一个文件的地方,无论是通过 id 删除,从数据库中删除它我是这样做的:

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.问候。

You can write a signal handler for post_delete that takes care of deleting the files after the object in the database is deleted:您可以为post_delete编写一个信号处理程序,它负责在数据库中的对象被删除后删除文件

@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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM