I've got the following model in my Django app:
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
)
I've set the MEDIA_ROOT to a directory called /hmedia/ inside my Apache web root, and I've set MEDIA_URL to 'http://localhost/hmedia/'
. This seems to have worked – I've successfully uploaded a couple of images through the Django admin site, and I can view those images via http://localhost/hmedia/images/[filename]
. And the Django admin site actually shows me the filename, and links to the live URL for each image, and the links work.
My problem is, I can't work out how to get the URLs or filenames of these images in my template:
<ul>
{% for image in article.image_set.all %}
<li>Caption: "{{image.caption}}", Credit: "{{image.credit}}", URL: "{{image.url}}"</li>
{% endfor %}
</ul>
The above template results in this output:
<ul>
<li>Caption: "here's an image caption", Credit: "some photographer", URL: ""</li>
<li>Caption: "Another caption here", Credit: "Another photographer", URL: ""</li>
</ul>
In other words, it correctly outputs the caption and credit properties of each image, but it outputs nothing for {{image.url}}.
How do I get the image's URL in my template? How does the Django admin interface template do it? (I've rooted around in the admin templates directory but can't find what I'm looking for.)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…