How to get an ImageField URL within a template?

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.


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.

Tags:

Python

Django