gpt4 book ai didi

python - 动态上传路径 - 包括原始字段

转载 作者:太空狗 更新时间:2023-10-30 02:34:41 24 4
gpt4 key购买 nike

我有一个包含多个 ImageField 的 Django 模型,并使用一个可调用对象来确定上传路径。我想在上传路径中包含原始上传字段的名称,在本例中为 tinysmallmediumpress.

我能想到的唯一方法是创建一个 pre_save 接收器,用 uuid 替换 file.name。然后 upload_to 可调用文件通过将其与 filename 进行比较来找到匹配项。有没有更简单的方法来做到这一点?

class SomeDjangoModel(models.Model):

IMAGE_SIZES = ('tiny', 'small', 'medium', 'press')

def image_path(self, filename):
""" Example return: [some-django-model]/[medium]/[product1].[jpg] """
size = None
for field_name in self.IMAGE_SIZES:
field_fn = getattr(getattr(self, field_name), 'name', '')
if field_fn == filename.rpartition('/')[2]:
size = field_name
break

return u'{}/{}/{}.{}'.format(
slugify(self._meta.verbose_name),
size or 'undetermined',
self.slug,
filename.rpartition('.')[2].lower(),
)

tiny = models.ImageField(upload_to=image_path, blank=True, null=True)
small = models.ImageField(upload_to=image_path, blank=True, null=True)
medium = models.ImageField(upload_to=image_path, blank=True, null=True)
press = models.ImageField(upload_to=image_path, blank=True, null=True)

pre_save 接收器:

@receiver(pre_save, sender=SomeDjangoModel)
def set_unique_fn(sender, instance, **kwargs):
""" Set a unique (but temporary) filename on all newly uploaded files. """

for size in instance.IMAGE_SIZES:
field = getattr(instance, '{}_img'.format(size), None)
if not field:
continue
fieldfile = getattr(field, 'file', None)
if isinstance(fieldfile, UploadedFile):
fieldfile.name = u'{}.{}'.format(
uuid.uuid4().hex,
fieldfile.name.rpartition('.')[2],
)

最佳答案

您可以更改 image_path() 以便它返回一个已知大小的可调用对象:

def image_path(size):
def callback(self, filename)
""" Example return: [some-django-model]/[medium]/[product1].[jpg] """
return u'{}/{}/{}.{}'.format(
slugify(self._meta.verbose_name),
size,
self.slug,
filename.rpartition('.')[2].lower(),
)
return callback

class SomeDjangoModel(models.Model):
tiny = models.ImageField(upload_to=image_path('tiny'), blank=True, null=True)
small = models.ImageField(upload_to=image_path('small'), blank=True, null=True)
medium = models.ImageField(upload_to=image_path('medium'), blank=True, null=True)
press = models.ImageField(upload_to=image_path('press'), blank=True, null=True)

关于python - 动态上传路径 - 包括原始字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6889156/

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