我有一个带有多个 ImageField 的 Django 模型,并使用可调用来确定上传路径。我想在上传路径中包含原始上传字段的名称,在本例tiny
中为small
、medium
或press
。
我能想到的唯一方法是创建一个file.name
用 uuid 替换的 pre_save 接收器。然后 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],
)