我想更改图像名称及其上传时的存储位置。
我有
def name_func(instance, filename):
blocks = filename.split('.')
ext = blocks[-1]
filename = "%s.%s" % (instance.id, ext)
return filename
class Restaurant(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
image_file = models.ImageField(upload_to=name_func,null=True)
class Bar(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
image_file = models.ImageField(upload_to=name_func,null=True)
这会将所有图像文件上传到媒体文件夹中,并为其提供实例的 ID 作为名称。
现在我希望将图像文件上传到两个不同的子文件夹中。所以我尝试使用系统文件存储:
fs_restaurant = FileSystemStorage(location='media/restaurant')
fs_bar = FileSystemStorage(location='media/bar')
然后将 image_file
字段更改为:
image_file = models.ImageField(upload_to=name_func,null=True, storage=fs_restaurant)
和
image_file = models.ImageField(upload_to=name_func,null=True, storage=bar)
现在,这会将文件保存在正确的文件夹结构中,但是,当我单击管理面板中的链接时,它的链接不正确。这显然是针对 name_func 函数的,但我想知道是否有办法纠正它?在文档中我找不到存储类中的命名函数。
关于如何解决这个问题有什么想法吗?
最佳答案
我认为你的问题是你需要将子文件夹添加到你的文件名中并返回它。在数据库中,文件名应该是 STATIC_URL
或 MEDIA_URL
到文件的相对路径。
下面是我为文件名生成 UUID 并将其放入名为 app_images
的子文件夹中的示例。
def unique_filename(instance, filename):
path = 'app_images'
filetype = os.path.splitext(instance.image.name)[1]
new_filename = "{}{}".format(uuid.uuid4().hex, filetype)
while AppImage.objects.filter(image__contains=new_filename).exists():
new_filename = "{}{}".format(uuid.uuid4().hex, filetype)
instance.filename = filename
return os.path.join(path, new_filename)
关于python - 如何在django中更改上传文件的名称和存储位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37737587/