Rendering images from static folder in Django

Haider Ali
Python and Django
Published in
2 min readDec 30, 2023

It took three days to fix the problem of rendering images from static folder in Django and that’s the reason I am writing this article.

I am in the development phase of developing a quiz application in Python Django. I cam across the problem of rendering images in my app.

The issue was that when I run the app on localhost the images were displayed, but when I uploaded my web app on the server (on render.com) the images where not picked and hence not displayed.

In django files that are used by the app are stored in the ‘static’ folder which is inside the main project folder.

Directory structure of a django app

We need to add following to ‘settings.py’ file:

STATIC_URL = "static/"
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]

These settings worked fine when I run app on local host. But when I uploaded my app on render.com the images were not displayed. I asked Stackoverflow, ChatGPT, Googled, watched YouTube videos but didn’t get any help.

After regourous searches I fixed the problem!

The solution is:

Install the whitenoise package:

pip install whitenoise

Add ‘whitenoise.middleware.WhiteNoiseMiddleware’, in the settings.py file. But remember: add the line just after the line: 'django.middleware.security.SecurityMiddleware'

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]

Entries in ‘settings.py’ should look like:


if not DEBUG:
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]

Hope that Django developers who host their apps on render.com will find this article useful.

If article was useful clap for it.

Cheers!

--

--