Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

python - How to get an ImageField URL within a template?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you need is {{ image.image.url }} & {{ image.image.path }}, while {{ image }} - just an Image object, instance of the defined model and {{ image.image }} gets us to the field which is ImageField object and provides all the specified attributes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...