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.
- Open the urls.py folder under the web app folder.
- Add the statement to staticfiles_urlpatterns if it is not already available.
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
- Add this line to the end of the same urls.py file if it is not already available.
urlpatterns += staticfiles_urlpatterns()
- Here is the sample urls.py in the web app. In this, my web app is named as dj_app.
- 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.
- Add the image to this new folder static/dj_app/media.
- 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" />
Python Django web page with image
Related Article
Reference
- About using static files in Django at Django Docs.
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
Hi, Happy to know that this article helped you.
This was very helpful for me! Thankyou so much for precisely giving us what to do
Thank you. Great to hear that this article helped you.