首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django imagekit和动态路径

Django imagekit和动态路径
EN

Stack Overflow用户
提问于 2012-01-16 17:43:34
回答 1查看 972关注 0票数 1

我正在使用imagekit提供的imagekit

因此,我定义了两个类模型:

代码语言:javascript
复制
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 

问题是每一张照片都是在“静态/照片”路径中创建的。我的目的是保存图像和缩略图,以及基于国家名称的动态路径。

例如,对于国家/地区“阿根廷”,动态路径将是“静态/照片/阿根廷/”

我如何才能做到这一点?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-01-31 07:39:22

看起来你混合了两个不同版本的ImageKit。较新的版本(1.0+)不再使用内部IKOptions类,因此所有这些都被忽略了。(还删除了save_count_as功能。)

如果您想控制缓存文件名,ImageSpec构造函数将接受一个cache_to kwarg,它可以像ImageFieldupload_to-can一样被调用。

代码语言:javascript
复制
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.

因此,您只需创建一个接受这些参数并返回所需路径的函数,并在模型中使用该路径,如下所示:

代码语言:javascript
复制
class Photo(models.Model):
    thumbnail = ImageSpec(..., cache_to=my_cache_to_function)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8878119

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档