栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

ImageField覆盖具有相同名称的图像文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ImageField覆盖具有相同名称的图像文件

是的,这对我也很重要。这就是我所做的。

模型:

from app.storage import OverwriteStorageclass Thing(models.Model):    image = models.ImageField(max_length=SOME_CONST, storage=OverwriteStorage(), upload_to=image_path)

还定义在

models.py
中:

def image_path(instance, filename):    return os.path.join('some_dir', str(instance.some_identifier), 'filename.ext')

在另一个文件中,

storage.py

from django.core.files.storage import FileSystemStoragefrom django.conf import settingsimport osclass OverwriteStorage(FileSystemStorage):    def get_available_name(self, name):        """Returns a filename that's free on the target storage system, and        available for new content to be written to.        Found at http://djangosnippets.org/snippets/976/        This file storage solves overwrite on upload problem. Another        proposed solution was to override the save method on the model        like so (from https://pre.djangoproject.com/ticket/11663):        def save(self, *args, **kwargs): try:     this = MyModelName.objects.get(id=self.id)     if this.MyImageFieldName != self.MyImageFieldName:         this.MyImageFieldName.delete() except: pass super(MyModelName, self).save(*args, **kwargs)        """        # If the filename already exists, remove it as if it was a true file system        if self.exists(name): os.remove(os.path.join(settings.MEDIA_ROOT, name))        return name

显然,这些是这里的示例值,但是总体而言,这对我来说效果很好,并且根据需要进行修改应该非常简单。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/383663.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号