django-imagekit获取模型属性 [英] django-imagekit get model attribute
本文介绍了django-imagekit获取模型属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下模型:
class PropertyPhoto(models.Model):
property = models.ForeignKey('Property')
photo_show = ProcessedImageField(upload_to=get_web_watermark,
processors=[Watermark()],
options={'quality': 95})
和自定义水印类:
class Watermark(object):
def process(self, image):
try:
this_property = Property.objects.get(pk=*self.property.id*)
except Property.DoesNotExist:
print "error"
我该如何从Watermark类内部访问我的模型属性 property?
How do I access my model attribute "property" from inside Watermark class?
谢谢
推荐答案
您需要创建一个自定义规范,该规范从模型中获取您所需的信息,并将其传递给处理器。该文档显示示例:
You'll need to create a custom spec that gets the information you need from the model and passes it to your processor. The docs show an example:
from django.db import models
from imagekit import ImageSpec, register
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill
from imagekit.utils import get_field_info
class AvatarThumbnail(ImageSpec):
format = 'JPEG'
options = {'quality': 60}
@property
def processors(self):
model, field_name = get_field_info(self.source)
return [ResizeToFill(model.thumbnail_width, thumbnail.avatar_height)]
register.generator('myapp:profile:avatar_thumbnail', AvatarThumbnail)
class Profile(models.Model):
avatar = models.ImageField(upload_to='avatars')
avatar_thumbnail = ImageSpecField(source='avatar',
id='myapp:profile:avatar_thumbnail')
thumbnail_width = models.PositiveIntegerField()
thumbnail_height = models.PositiveIntegerField()
请注意,您可以将规范直接传递给 ImageSpecField
构造函数(使用 spec
kwarg),而不是如上所示,使用一个id(并使用 id
kwarg)注册它。
Note that you can pass the spec directly to the ImageSpecField
constructor (using the spec
kwarg) instead of registering it with an id (and using the id
kwarg) as shown above.
这篇关于django-imagekit获取模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文