标签:python django django-models django-signals
我有一个带有多个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,django,django-models,django-signals 来源: https://codeday.me/bug/20190530/1186464.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。