Django images not showing up in template

Question:

I’ve spent the whole day trying to find a solution for showing the images in the template but I couldn’t find any solution to my case.

This is my settings

STATIC_URL = '/static/'

MEDIA_URL = '/media/'

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

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

STATICFILES_DIRS = [
 os.path.join(BASE_DIR, 'DataCallGuide/static')
]

My model

class TroubleshootingSteps(models.Model):

    box_header = models.CharField(blank=True, null=True, max_length=250)
    box_content = models.CharField(blank=True, null=True, max_length=250)
    box_botton = models.CharField(blank=True, null=True, max_length=250)

    header = models.TextField(blank=True, null=True)
    sub_header = models.TextField(blank=True, null=True)
    text1 = models.TextField(blank=True, null=True)
    image1 = models.ImageField(blank=True, null=True, upload_to="images/")

and the template

{% extends 'base.html' %}
{% load static %}
{% block content %}

 <div class="container overflow-hidden">
  <div class="text-center">
   <h4 class="mt-5 mb-5">{{data.header}}</h4>
  </div>

  <h3 dir="rtl" class="rtlss">{{data.sub_header}}</h3>
  <img src="{{ data.image1.url }}">

  </div>

{% endblock%}

Also when I click on the image link in admin pages it doesn’t show the image and display page not found error with the below link
http://127.0.0.1:8000/media/images/IMG-20220901-WA0009.jpg
What is wrong please?

Asked By: Islam Fahmy

||

Answers:

Did you modified your url.py?

urlpatterns = [
    Your urls
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Answered By: saro

instead of this:

 <img src="{{ data.image1.url }}">

Try this way:

<img src="/media/{{ data.image1 }}">
Answered By: Manoj Tolagekar

If images not load from static folder then do this

# do comment static root path

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

# add static dirs path like this

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

#----------- OR ---------------

STATICFILES_DIRS = [BASE_DIR / 'static']

If images not load from media folder then do this

# --------- Show Image in Html   ---------

# Add Code in Project (urls.py)
from django.contrib import admin
from django.urls import path,include

from django.conf import settings # --------> this
from django.conf.urls.static import static # --------> this

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # --------> this

# Add Code in Project (setting.py)
# MEDIA_ROOT =  os.path.join(BASE_DIR, 'media') 
MEDIA_ROOT =  BASE_DIR / 'media' 
MEDIA_URL = '/media/'