我使用的是imagekit
提供的imagekit所以,我已经定义了两个类模型:
class Photo(models.Model):
#photo_wrapper = models.ForeignKey(PhotoWrapper, blank=True, null=True)
original_image = models.ImageField(upload_to='static/photos')
thumbnail = ImageSpec([Adjust(contrast=1.2, sharpness=1.1),
resize.Crop(50, 50)], image_field='original_image',
format='JPEG', quality=90)
num_views = models.PositiveIntegerField(editable=False, default=0)
class IKOptions:
# This inner class is where we define the ImageKit options for the model
spec_module = 'myspecs.specs'
cache_dir = 'static/photos'
image_field = 'original_image'
save_count_as = 'num_views'
class Country(models.Model):
country_name = models.CharField(max_length=250)
country_photo = models.ForeignKey(Photo, blank=True, null=True)
def __unicode__(self):
return '%s' % self.country_name
问题是每张照片都是在“静态/照片”路径中创建的。 我的目的是根据国家名称以动态路径保存图像和缩略图..
例如,对于国家“阿根廷”,动态路径将是“静态/照片/阿根廷/”
我该如何实现?
答案 0 :(得分:1)
看起来你正在混合两个不同版本的ImageKit。较新的版本(1.0+)不再使用内部IKOptions
类,因此所有这些都被忽略。 (save_count_as功能也被删除了。)
如果要控制缓存文件名,ImageSpec
构造函数接受cache_to
kwarg,类似ImageField
的{{1}} - 可以是可调用的。以下是upload_to
的当前文档:
cache_to
所以你只需要创建一个接受这些参数的函数并返回你想要的路径,并在你的模型中使用它,如下所示:
Specifies the filename to use when saving the image
cache file. This is modeled after ImageField's ``upload_to`` and
can be either a string (that specifies a directory) or a
callable (that returns a filepath). Callable values should
accept the following arguments:
- instance -- The model instance this spec belongs to
- path -- The path of the original image
- specname -- the property name that the spec is bound to on
the model instance
- extension -- A recommended extension. If the format of the
spec is set explicitly, this suggestion will be
based on that format. if not, the extension of the
original file will be passed. You do not have to use
this extension, it's only a recommendation.