当具有相同名称的文件已经存在时,如何防止Django更改文件名? [英] How to prevent Django from changing file name when a file with that name already exists?

查看:253
本文介绍了当具有相同名称的文件已经存在时,如何防止Django更改文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就我而言,我允许用户上传头像图片,并使用user_id作为文件名.因此会有1.jpg,2.jpg等

In my case I allow user to upload an avatar picture and use user_id as filename, simply. So there will be 1.jpg, 2.jpg, etc.

但是我发现如果我为某个已经上传了一个帐户的帐户上传一个新的化身,假设用户#10,新文件将被命名为"10_1.jpg".可以,但是我不需要它,我希望新文件可以覆盖旧文件-仍然可以节省一些磁盘空间.

However I found if I upload a new avatar for some account that already has one uploaded, let's say user #10, the new file will be named as "10_1.jpg". This is OKay, however I don't need it and I hope new file could overwrite the old one - it also saves some disk space anyway.

我用Google搜索和搜索,但找不到线索.我希望可以为ImageField或FileField提供一个选项,但是它不存在.

I googled and searched but couldn't find a clue. I was hoping there would be an option for ImageField or FileField but it's not there.

感谢帮助!

推荐答案

您应该定义自己的存储,从FileSystemStorage继承它,并覆盖其中的get_available_name函数.使用此存储空间作为您的imagefield. 像这样:

You should define your own storage, inherit it from FileSystemStorage, and override get_available_name function in it. The use this storage for your imagefield. Something like this:

class OverwriteStorage(FileSystemStorage):

    def get_available_name(self, name):
        if self.exists(name):
            os.remove(os.path.join(SOME_PATH, name))
        return name

fs = OverwriteStorage(location=SOME_PATH)

class YourModel(models.Model):
    image_file = models.ImageField(storage=fs)

这篇关于当具有相同名称的文件已经存在时,如何防止Django更改文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆