python – 动态上载路径 – 包括原始字段
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 动态上载路径 – 包括原始字段,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2179字,纯文字阅读大概需要4分钟。
内容图文
![python – 动态上载路径 – 包括原始字段](/upload/InfoBanner/zyjiaocheng/815/6beeea959a3c4d2dbc45c391a44247a5.jpg)
我有一个带有多个ImageFields的Django模型,并使用callable来确定上传路径.我想在上传路径中包含原始上传字段的名称,在这种情况下,微小,小,中或按.
我能想到的唯一方法是创建一个pre_save接收器,用uuid替换file.name.然后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],
)
解决方法:
您可以更改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 – 动态上载路径 – 包括原始字段全部内容,希望文章能够帮你解决python – 动态上载路径 – 包括原始字段所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。