4

複数のImageFieldを持つDjangoモデルがあり、呼び出し可能オブジェクトを使用してアップロードパスを決定しています。元のアップロードフィールドの名前をアップロードパスに含めたいと思います。この場合はtiny、、、smallまたはmediumですpress

file.name私が考えることができる唯一の方法は、uuidで置き換えるpre_saveレシーバーを作成することでした。次に、upload_to callableは、と比較して一致するものを見つけ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],
            )
4

1 に答える 1

6

image_path()サイズをすでに知っている callable を返すように変更できます。

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)
于 2011-07-31T12:07:09.097 に答える