I'm having trouble serving media files on my Django application deployed on Render. The media files are being created and stored (I think?) correctly on the server, but accessing them through the browser results in a 404 error. Everything works fine in my local development environment.
Project Setup:
settings.py
:
# Initialize environment variables
env = environ.Env(
DEBUG=(bool, False)
)
# Read .env file
environ.Env.read_env(os.path.join(Path(__file__).resolve().parent.parent, '.env'))
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Static and Media files
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = '/var/data/media'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
# Static files finders
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
# Ensure static files are served using Whitenoise
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',
'allauth.account.middleware.AccountMiddleware',
]
# Whitenoise storage
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Other settings...
# URL configuration
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
File Existence:
I have verified that the media files are being created on the server:
render@srv-cpoif12ju9rs738p174g-5f676c9f8c-bwxhd:~/project/src$ ls -l /var/data/media/subtitles/U-sEgjJRHcM_subtitles.json
-rwxr-xr-x 1 render render 14995 Jun 22 14:53 /var/data/media/subtitles/U-sEgjJRHcM_subtitles.json
URL Patterns:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Issue:
Despite the file existing on the server, accessing it via the URL results in a 404 error.
For example: https://xxx.onrender.com/media/subtitles/U-sEgjJRHcM_subtitles.json
What I've Tried:
- Verified file existence on the server.
- Checked and double-checked
MEDIA_URL
andMEDIA_ROOT
settings. - Ensured URLs are correctly configured.
- Permissions seem correct with
chmod -R 755 /var/data/media
.
Additional Info:
- Using Render for deployment.
- Created a persistent disk mounted at
/var/data
.
Any help to resolve this issue would be greatly appreciated!