在 views.py 中是否有使用 Wagtail Image 标签的解决方法

Is there a workaround for using Wagtail Image tags in views.py

我遇到了以下问题: 在我的 models.py 中,我使用的是这样的鹡鸰图像:

class ArtWork(models.Model):
    image = models.ForeignKey(
            'wagtailimages.Image',
            on_delete=models.CASCADE,
            related_name='+'
        )
    ...
    ...
    ...

我知道我现在可以像这样在我的模板中使用图片了:

{% image artwork.image height-100 %}

但是对于我当前的项目,我需要在 views.py 中使用图像标签,因为我想用它生成 Pdf。

通过简单地使用 artwork.image 只是图片的标题 returns 但我需要这样的东西:

<img alt="SomeName" src="/media/images/SomeName_155x200.max-1200x1200_22b3pND.height-100.jpg" width="77" height="100"> 

artwork.image.url没有结果。 如何在我的模板之外使用 Wagtail 图像?

模板标签只是函数,您可以找到代码 on github. The image tag relies on the models Filter and Rendition

我建议阅读该代码以了解其工作原理,然后在您的视图中使用它。

如果您需要 URL 演绎版(缩略图),您可以执行以下操作:

artwork_page_object.image.get_rendition('height-100').url

或访问演绎版文件:

artwork_page_object.image.get_rendition('height-100').file

您可以对 image 模板标签使用任何有效的调整大小方法,而不是 height-100(参见 the documentation for the image 标签)

如果你想访问原始图像,你可以这样做:

artwork_page_object.image.file

有用的文档: