gpt4 book ai didi

django - ImageField 覆盖同名图像文件

转载 作者:行者123 更新时间:2023-11-28 19:34:20 25 4
gpt4 key购买 nike

我有模型 UserProfile 和字段 avatar = models.ImageField(upload_to=upload_avatar)

upload_avatar 函数根据user.id 命名图像文件(例如12.png)。

但是当用户更新头像时,新头像名称与旧头像名称一致,Django 会为文件名添加后缀(例如 12-1.png)。

有办法覆盖文件而不是创建新文件吗?

最佳答案

是的,我也遇到了这个问题。这是我所做的。

型号:

from app.storage import OverwriteStorage

class 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 FileSystemStorage
from django.conf import settings
import os

class 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://code.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

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

关于django - ImageField 覆盖同名图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9522759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com