如何在字段定义之外的 Django imagekit 中指定图像规格?
How to specify image specs in Django imagekit outside the field definition?
我有以下模型定义:
class Photo(models.Model) :
def get_gallery_path(self, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return 'static/uploads/images/gallery/' + filename
uploader = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(default=date.today)
image = ProcessedImageField(default='', verbose_name='Image', upload_to=get_gallery_path, processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60})
caption = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return str(self.id) + str(self.uploader.username) + str(self.date)
class Meta:
verbose_name_plural = "Photos"
verbose_name = "Photo"
我使用django-imagekit修改上传的图片。但如您所见,我必须在 image
字段中内联说明所有属性和选项。当我指定许多属性时,这会使代码难以阅读。
有没有办法在 models.py
文件中单独定义属性和选项,以便我可以将其用于所有图像字段。
您可以简单地利用字典解包。
例如定义你的字典processed_image_field_specs
:
def get_gallery_path(filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return 'static/uploads/images/gallery/' + filename
processed_image_field_specs = {
'default': '',
'verbose_name': 'Image',
'upload_to': get_gallery_path,
'processors': [ResizeToFill(100, 50)],
'format': 'JPEG',
'options': {'quality': 60}
}
现在解压字典,为 ProcessedImageField
:
提供命名参数
class Photo(models.Model) :
...
image = ProcessedImageField(**processed_image_field_specs)
...
我有以下模型定义:
class Photo(models.Model) :
def get_gallery_path(self, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return 'static/uploads/images/gallery/' + filename
uploader = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(default=date.today)
image = ProcessedImageField(default='', verbose_name='Image', upload_to=get_gallery_path, processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60})
caption = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return str(self.id) + str(self.uploader.username) + str(self.date)
class Meta:
verbose_name_plural = "Photos"
verbose_name = "Photo"
我使用django-imagekit修改上传的图片。但如您所见,我必须在 image
字段中内联说明所有属性和选项。当我指定许多属性时,这会使代码难以阅读。
有没有办法在 models.py
文件中单独定义属性和选项,以便我可以将其用于所有图像字段。
您可以简单地利用字典解包。
例如定义你的字典processed_image_field_specs
:
def get_gallery_path(filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return 'static/uploads/images/gallery/' + filename
processed_image_field_specs = {
'default': '',
'verbose_name': 'Image',
'upload_to': get_gallery_path,
'processors': [ResizeToFill(100, 50)],
'format': 'JPEG',
'options': {'quality': 60}
}
现在解压字典,为 ProcessedImageField
:
class Photo(models.Model) :
...
image = ProcessedImageField(**processed_image_field_specs)
...