[Django]-How to get an ImageField URL within a template?

51👍

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.

1👍

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.

1👍

if you have ImageForm in forms.py and passing Form Instance to your django template
then src=”{% get_media_prefix %}{{your-form-instance.instance.image}}” will solve your issue.

models.py

class Addon(models.Model):
    image = models.FileField(upload_to='addons/', null=True)
    addon_name = models.CharField(max_length=100, null=False, blank=False)

forms.py

class AddonForm(forms.ModelForm):
    addon_name = forms.CharField(max_length=100, required=True)
    image = forms.ImageField(required=False)

views.py

@require_http_methods(['GET'])
def addons(request, ):
    addon_form_set = modelformset_factory(Addon, form=AddonForm, extra=1)
    addon_forms = addon_form_set(queryset=Addon.objects.all())
    return render(request, 'addons/addons.html', {'form': addon_forms)

your_templates.html

{% for data in form %}
   <img src="{% get_media_prefix %}{{data.instance.image}}"/>
{% endfor %}

-8👍

Create a folder “static” in you’re django project and add this to you’re settings file

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

If you don’t have this line in you’re settings file also add it

BASE_DIR = os.path.dirname(os.path.dirname(__file__))

Now in the template you can use

{% static  image.image.url %}

Leave a comment