I want to serve all types of media files in my Django Project I used Whitenoise to server static files and static files are working well but I’m having issues with serving images that are uploaded by users (I’m using Linux shared hosting Cpanel)
Directory structure
Project_name
App_1
App_2
Staticfiles (that are collected via collectstatic cmd)
manage.py
passenger_wsgi.py
and here is the project’s settings.py
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATIC_URL = '/static/'
MEDIA_URL = ''
STATICFILES_DIRS =[
BASE_DIR/ 'static'
]
MEDIA_ROOT = BASE_DIR / 'staticfiles/images'
and file urls.py
urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
3
Answers
Whitenoise only checks for static files at startup and so files added after the app starts won’t be seen.
Since, Whitenose is not suitable for serving user-uploaded media files.
Please check Whitenose official docs. http://whitenoise.evans.io/en/latest/django.html#serving-media-files
If you want to serve media from django in production just create your own
static
function based on original static function like this:Though it is not recommended, you can need it if you are not using ngingx/apache and have a small server.
My case is I am using whitenoise and gunicorn to serve on local server.
You can serve media files by creating a view for media file.
In
myapp.views.py
Now add url in app
myapp.urls.py
in
settings.py