Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an ImageField URL within a template?

Tags:

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.)

like image 253
callum Avatar asked Jan 13 '12 12:01

callum


2 Answers

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.

like image 75
S.Kozlov Avatar answered Mar 12 '23 16:03

S.Kozlov


Change your code to this:

<ul>
{% for image in article.image_set.all %}
    <li>Caption: "{{ image.caption }}", Credit: "{{ image.credit }}", URL: "<a href ='/{{ image.image }}'{{ image.image }}</a>"</li>
{% endfor %}
</ul>

Change {{ image.url }} to {{ image.image }} because '.image' contains the location of the image. The reason that you don't get any value from '.url' is that you don't have a field url in your class Image in your models.

like image 37
Amazing Angelo Avatar answered Mar 12 '23 16:03

Amazing Angelo