'serving media files in Django for Production
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)
Solution 1:[1]
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
Solution 2:[2]
If you want to serve media from django in production just create your own static
function based on original static function like this:
#my_app/static.py
import re
from urllib.parse import urlsplit
from django.core.exceptions import ImproperlyConfigured
from django.urls import re_path
from django.views.static import serve
def static(prefix, view=serve, **kwargs):
"""
Return a URL pattern for serving files in debug mode.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
"""
if not prefix:
raise ImproperlyConfigured("Empty static prefix not permitted")
elif urlsplit(prefix).netloc: # <- removed DEBUG from this line
# No-op if non-local prefix.
return []
return [
re_path(
r"^%s(?P<path>.*)$" % re.escape(prefix.lstrip("/")), view, kwargs=kwargs
),
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Yery cs |
Solution 2 | mka |