【发布时间】:2012-01-13 12:24:07
【问题描述】:
我的 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
)
我已将 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>
上面的模板结果如下:
<ul>
<li>Caption: "here's an image caption", Credit: "some photographer", URL: ""</li>
<li>Caption: "Another caption here", Credit: "Another photographer", URL: ""</li>
</ul>
换句话说,它正确地输出了每张图像的标题和信用属性,但它没有为 {{image.url}} 输出任何内容。
如何在模板中获取图片的 URL? Django 管理界面模板是如何做到的? (我已经在管理模板目录中找到了根,但找不到我要找的东西。)
【问题讨论】:
-
您只需要访问图像字段本身的 .path 和 .url - 所以
image.image.path、image.image.url。照原样,您正在尝试访问模型实例上不存在的那些属性。