Django easy_thumbnails的默认图片

nak*_*nak 4 django easy-thumbnails

我有一个使用easy_thumbnails(| thumbnail_url)显示的ImageField模型.
我的问题是如果ImageField为空,我如何显示默认图像?
我想在模型/视图中使用此逻辑,而不是在html /模板中.

例如:

DEFAULT_PICTURE = 'default.jpg'

def get_picture(self):
    if self.picture:
        return self.picture
    else:
        from DEFAULT_PICTURE
Run Code Online (Sandbox Code Playgroud)

get_picture()返回哪个对象与easy_thumbnails兼容?
我尝试创建一个新的File对象,就像这里一样,但它没有用.
您能否提供一个返回现有文件以使用easy_thumbnails显示的工作示例?

nak*_*nak 6

Chris(easy_thumbnails)在这里回答,也在SO上回答.

他建议创建一个新的ImageFieldFile很好,但是easy_thumbnails stilled失败了,因为新创建的ImageFieldFile有一个空实例.
所以要么设置instance = self:

DEFAULT_PICTURE = 'default.jpg'

def get_picture(self):
    if self.picture:
        return self.picture
    else:
        return ImageFieldFile(instance=self, field=FileField(), name=DEFAULT_PICTURE)
Run Code Online (Sandbox Code Playgroud)

或更改alias.py第116行:

if not hasattr(target, 'instance'):
    return None
Run Code Online (Sandbox Code Playgroud)

应该...

if not hasattr(target, 'instance') or not target.instance:
    return None
Run Code Online (Sandbox Code Playgroud)