7. Exhibiting media and images
Adjusting the settings.py file
We will now display product images on our store page. To achieve this, insert an <img>
tag within the for-loop in the store.html
file to render each product's image.
{% for product in products %}
<img src="{{ product.image.url }}" width = "300" height = "450"> <!--returns the url of the image -->
<p>Product: {{ product.name }}</p>
However, when we run the page the images will be loaded but won't exhibit anything. This is because when we open the image in a new tab, we see that they are inside this url:

urls.py
file. In order to fix this, first we will go inside the settings.py
file and add the following lines of code:
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')
MEDIA_URL = "images/"
As of now, the images added via the admin page are being saved on the main ecommerce project folder, the MEDIA_ROOT
variable now specifies where all image files should be saved
IMPORTANT: If you currently have any saved images outside the folder specified on the MEDIA_ROOT, move them into it.
On the other hand, the MEDIA_URL
variable specifies what url all images will have, in this case they will have their url starting with 'images/'
Including the new urls
Now, inside the urls.py file of the main ecommerce folder, NOT the one of the store folder, add this line of code:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This setup adds all URLs starting with 'image/' from the MEDIA_URL
, sourcing images from the directory defined by MEDIA_ROOT
.
We will also need to import the static and settings functions at the start of the code:
from django.conf.urls.static import static
from django.conf import settings
Finally, when we run the page, our images will be properly displayed:

These changes were made directly on the main ecommerce urls.py
file as we want the images to be managed on the same way for all apps
Last updated