gpt4 book ai didi

Django ImageField 在上传时更改文件名

转载 作者:行者123 更新时间:2023-11-28 19:35:42 29 4
gpt4 key购买 nike

保存模型“产品”后,我希望上传的图像与 pk 的名称相同,例如 22.png 或 34.gif 我不想仅更改名称的图像格式。如何才能做到这一点?到目前为止我的模型示例......

image = models.ImageField(
upload_to="profiles",
height_field="image_height",
width_field="image_width",
null=True,
blank=True,
editable=True,
help_text="Profile Picture",
verbose_name="Profile Picture"
)
image_height = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100")
image_width = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100")

最佳答案

您可以将函数传递到 upload_to 字段:

def f(instance, filename):
ext = filename.split('.')[-1]
if instance.pk:
return '{}.{}'.format(instance.pk, ext)
else:
pass
# do something if pk is not there yet

我的建议是返回一个随机文件名而不是 {pk}.{ext}。作为奖励,它会更安全。

Django 会调用这个函数来确定文件应该上传到哪里。这意味着您的函数负责返回文件的整个路径,包括文件名。下面是修改后的函数,您可以在其中指定上传到何处以及如何使用它:

import os
from uuid import uuid4

def path_and_rename(path):
def wrapper(instance, filename):
ext = filename.split('.')[-1]
# get filename
if instance.pk:
filename = '{}.{}'.format(instance.pk, ext)
else:
# set filename as random string
filename = '{}.{}'.format(uuid4().hex, ext)
# return the whole path to the file
return os.path.join(path, filename)
return wrapper

FileField(upload_to=path_and_rename('upload/here/'), ...)

关于Django ImageField 在上传时更改文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15140942/

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