minttux
minttux

Reputation: 435

Uploaded media doesn't server in production mode without restarting django

I need to serve media in Django in production mode and it is very little need to serve telegram user photos in Django admin. so I know everything about Django it's not for serving files or media so there is no need to repeat repetitive things. I just need to serve media in production mode for my purpose so I use WhiteNoise to do this and append this lines:

MIDDLEWARE = [
...
    'whitenoise.middleware.WhiteNoiseMiddleware',
...
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

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

in urls.py:

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('botAPI.urls')),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATICFILES_DIRS[0])
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
else:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

in wsgi.py I put this:

...
application = get_wsgi_application()
application = WhiteNoise(application, root=MEDIA_ROOT, prefix='/media/')
....

It works correctly and serves media files in production mode. but for new media for example uploading an image in Django admin I have to restart Django to access that media. is there any way to solve this problem or another way in Django to serve media files dynamically? (I can't use any external services cloud or CDN or webserver) everything should work with running Django

Upvotes: 0

Views: 46

Answers (1)

dev_light
dev_light

Reputation: 4106

You're probably mixing up static files and media files.

In Django, Static files are files that don't change while an application is running, and are sent to the browser when requested without needing to be generated by the server. Examples are CSS and Images. Media files are the files uploaded by users on the system.

WhiteNoise is used to serve static files for Python web apps. It is not suitable for serving user-uploaded “media” files because it only checks for static files at startup and so files added after the app starts won't be seen.

You can use Cloudinary to serve your media files in production. See Cloudinary on PyPi.

Upvotes: 0

Related Questions