Adding image to Python Django web app

In my earlier article, I have given the step by step instruction for adding static files like css and js files to Python Django we app. Now we will see how to add images to web app. Adding images and other media files is same as adding other static files. Sometime you may need to segregate images in a separate folder. Here, I have followed the steps as in creating & using static files in web app with separate folder.

  1. Open the folder under the web app folder.
  2. Add the statement to staticfiles_urlpatterns if it is not already available.
    • from django.contrib.staticfiles.urls import staticfiles_urlpatterns
  3. Add this line to the end of the same file if it is not already available.
    • urlpatterns += staticfiles_urlpatterns()
  4. Here is the sample in the web app. In this, my web app is named as dj_app.
    Setup the web app to use static files
  5. Create a folder for images (For this illustration I have named the folder as media) under the web app’s static folder static/dj_app.
  6. Add the image to this new folder static/dj_app/media.
    Adding image to Python Django web app
  7. To add the image file to a HTML template, open a template and add the the HTML img tag along with {% load static %} and {% static “<<image file url>>” %} placeholders, like this.
    • {% load static %} <img src="{% static "dj_app/media/house.jpg" %}" alt="home" />
Refering image file in a django web app template

Python Django web page with image

Python Django web page with image

Related Article


4 thoughts on “Adding image to Python Django web app”

  1. You cant belive how happy this web site made me. I was so hopeless and was not able to make a url of my media. Thanks a lot


Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.