'How can I get my image to display using django?

I cannot get my images to display on my webpage while using Django. All I see is the images 'alt' text displayed, and a broken image icon next to it. I'm able to successfully upload the image as originally intended. I'm using an Ubuntu AWS instance with Apache installed on it for my server. I also have Pillow installed for displaying images.

I'm also able to successfully load my CSS, so I know that it probably isn't an issue with my static directories or settings.

This is my settings.py file:

import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-)zp1^v$1v9%@3e*rz4yp0o964-^!8@ruff4$((b5vcv6*h@d-x'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['ec2-3-14-217-157.us-east-2.compute.amazonaws.com', '3.14.217.157']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'product.apps.ProductConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'productapp.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates']
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'productapp.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_ROOT = os.path.join(BASE_DIR, 'static')  # project level
STATIC_URL = 'static/'
# STATICFILES_DIRS = ['/var/www/productapp/static/']

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

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

LOGIN_REDIRECT_URL = 'index'
LOGOUT_REDIRECT_URL = 'index'

My urls.py file:

from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.http import HttpResponse
from django.urls import path, include


def home(request):
    return HttpResponse("Home page")


urlpatterns = [
    path('', TemplateView.as_view(template_name="index.html"), name="index"),
    path('admin/', admin.site.urls),
    path('accounts/', include('django.contrib.auth.urls')),
    path('productapp/', include('product.urls', namespace='product'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Since I'm using Apache I've tried editing the apache2.conf file to point to a specified media folder as follows:

Alias /media/ /var/www/prodictapp/media/
Alias /static /var/www/productapp/static/

<Directory /var/www/productapp/static>
Require all granted
</Directory>

<Directory /var/www/productapp/media>
Require all granted
</Directory>

WSGIScriptAlias / /var/www/productapp/productapp/wsgi.py
WSGIPythonPath /var/www/productapp

<Directory /var/www/productapp/productapp>
<Files wsgi.py>
Require all granted
</Files>
</Directory>

Template:

{% extends 'product/base.html' %}

{% block title %}{{ product.name }} - Details{% endblock %}

{% block body %}
    <h3>Details for {{ product.name }}:</h3>
    <p>
        Name: {{ product.name }}<br>
        Price: ${{ product.price }}<br>
        Description: {{ product.description }}<br>
        Quantity: {{ product.quantity }}<br>
        {% if product.image %} {# If record has image, display it #}
            Product image: <br><img src="{{ product.image.url }}" alt="{{ product.name }}"><br>
        {% endif %}
    </p>
{% endblock %}


Solution 1:[1]

You can try out this

<img src="{% static product.image.url %}" />            # use this 
<img src="{{ MEDIA_URL }}{{ product.image.url}}" />      # or this

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1