如何在模板中获取ImageField URL?

cal*_*lum 16 python django

我的Django应用程序中有以下模型:

class Image(models.Model):
    image = models.ImageField(
        upload_to='images/', 
        height_field='height', 
        width_field='width'
    )
    credit = models.CharField(max_length=50, blank=True)
    caption = models.TextField(blank=True)
    article = models.ForeignKey(Article)
    width = models.PositiveIntegerField(
        blank = True, null = True,
        editable = False,
        default = 0
    )
    height = models.PositiveIntegerField(
        blank = True, null = True,
        editable = False,
        default = 0
    )
Run Code Online (Sandbox Code Playgroud)

我已将MEDIA_ROOT设置为我的Apache Web根目录中名为/ hmedia /的目录,并且我已将MEDIA_URL设置为'http://localhost/hmedia/'.这似乎有效 - 我已成功通过Django管理站点上传了几张图片,我可以通过这些图片查看http://localhost/hmedia/images/[filename].Django管理站点实际上向我显示了文件名,并链接到每个图像的实时URL,并且链接有效.

我的问题是,我无法弄清楚如何在我的模板中获取这些图像的URL或文件名:

<ul>
{% for image in article.image_set.all %}
    <li>Caption: "{{image.caption}}", Credit: "{{image.credit}}", URL: "{{image.url}}"</li>
{% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)

以上模板导致此输出:

<ul>

    <li>Caption: "here's an image caption", Credit: "some photographer", URL: ""</li>

    <li>Caption: "Another caption here", Credit: "Another photographer", URL: ""</li>

</ul>
Run Code Online (Sandbox Code Playgroud)

换句话说,它正确输出每个图像的标题和信用属性,但它不会为{{image.url}}输出任何内容.

如何在模板中获取图像的URL?Django管理界面模板是如何做到的?(我已经在管理模板目录中扎根但无法找到我正在寻找的内容.)

小智 37

你需要{{ image.image.url }}&{{ image.image.path }},而{{ image }}- 只是一个Image对象