This is a long one.
I have a Django model named MediaModule
with an ImageField()
within the model.
The ImageField()
is configured in the following fashion:
article_image = models.ImageField(upload_to='assets/')
The above model is stored in a Django app named media
and directory setup is configured in the following fashion:
ROOT / media (app name) / assets / <image-name>
My settings.py
configuration in relation to the serving of images from within a Django model are as follows:
DEBUG = False
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'media',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
"whitenoise.middleware.WhiteNoiseMiddleware",
'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',
]
STORAGES = {
'default': {
'BACKEND': 'django.core.files.storage.FileSystemStorage',
},
"staticfiles": {
"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage",
},
}
STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_DIRS = [BASE_DIR / "static",]
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
In my <root>.urls
, file, I have the following:
from django.contrib import admin
from django.urls import path, include
from . import views
from django.conf import settings
from django.conf.urls.static import static
from django.views.static import serve
urlpatterns = [
path('admin/', admin.site.urls),
path('news/', include('media.urls')),
]
# Only for development. Do not use this in production.
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
in my media.urls
file; the following is configured:
from django.urls import path, include
from . import views
from django.contrib import admin
urlpatterns = [
path('articles/<str:article_identifier>', views.details),
]
In my media.views
file, I have the following:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from django.template import loader
from .models import MediaModule
from xxx import utils
def article_objects():
'''This will create an instance of the model to obtain all values from the model. It will then return the name of the model instance.s'''
articles = MediaModule.objects.all()
return articles
def details(request, article_identifier):
articles = article_objects()
article = get_object_or_404(MediaModule,article_identifier=article_identifier)
meta_object__image = utils.meta_object__image(article.article_image.url)
template = loader.get_template('media-article.html')
context = {
'article' : article,
'articles' : articles,
'meta_object__image' : meta_object__image,
}
return HttpResponse(template.render(context, request))
The relevant components of my MediaModule
model from within media.models
is as follows:
The generate_unique_number(char_length)
is a separate function which generates a random number which uniquely identifies a model object and appends it onto the URL, unrelated to the article_image
issue but included for continuity. It’s actually pretty cool!
from django.db import models
# Create your models here.
class MediaModule(models.Model):
article_identifier = models.CharField(primary_key=True, max_length=50, default="generate_unique_number(12)", unique=True)
article_image = models.ImageField(upload_to='assets/')
And lastly, from within my media-article.html
, image is called in the following way:
<img src="{{article.article_image.url}}" alt=""/>
Results
-
Upon checking the browser console, there are 404 error messages for the images. Browser console returns
http://127.0.0.1:8000/media/assets/<image-name>.jpeg
-
Inspecting the source
inspect source
, the image is being obtained from/media/assets/<img name>
-
All others images served from
staticfiles
have no issues with being shown. -
I’m failing to see why my browser is failing to find the image, despite said image being being placed in the correct folder directory with the relative directory in my model being
upload_to="assets/"
. -
From the web page, inspecting the source code, it only returns:
<img src="/media/assets/<image-name>" alt="">
-
Further information: this is a development environment.
If anybody needs anything clarifying or anything I’ve missed out, let me know.