Display Image in a Django Template (using ImageField)

This took me a lot of digging through the internet to figure it out and I hope it will help someone out there. After several trials, the solution here worked for me:

Follow this steps to load an image on your Django Template:

1. Add this to your settings file:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

2. Create a folder named “media” under your project root directory, meaning the folder will be on the same level as your apps

3. Add these to your main urls.py

from . import views, settings
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

4. In your model, use ImageField for the field being used for the image.

photo = models.ImageField(upload_to="gallery")

5. Add below to your template to load your images

If you are loading dynamically from a context object, use a syntax similar to this:

img src="{{ obj1.photo.url }}"

If you are loading statically, when the file name is already determined, use:

img src="/media/project_name/photo.png"

About Matthias 33 Articles
I am a Software Engineer from Houston, TX who love to write codes that brings great ideas to live. In my professional life, I have created software for different industries including Oil & Gas, Finance, Service Provider, Cloud Computing and Embedded Systems. When not writting codes, i enjoy travelling, good music and photography. You can reach me at me@matthiasomisore.com.


  1. What if the image may or may not exist? For example I tried:

    {% if post.image.url %}

    {% endif %}

    But if the image does not exist this errors out anyway. Any pointers?

3 Trackbacks / Pingbacks

  1. 【Django】ImageFieldを使って画像を表示する | yamagablog
  2. Djangoで画像を表示する方法 - 知的好奇心
  3. 【Django】How to upload image | yamagablog

Leave a Reply

Your email address will not be published.