Categories
Python Answers

How to include image files in Django templates?

Spread the love

To include image files in Python Django templates, to set the MEDIA_ROOT and MEDIA_URL settings.

For instance, in settings.py we add

MEDIA_ROOT = '<your_path>/media'
MEDIA_URL = '/media/'

to add MEDIA_ROOT and MEDIA_URL settings to add the media path.

And then we add

urlpatterns = patterns('',
               (r'^media/(?P<path>.*)$', 'django.views.static.serve',
                 {'document_root': settings.MEDIA_ROOT}),
              )

to add the static URL path to serve the image from.

And then in our template, we add

<img src="{{ MEDIA_URL }}<sub-dir-under-media-if-any>/<image-name.ext>" />

to get the image from /media/ with the path to the image.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *