Reputation: 873
Based on all I've read in the docs and on various s/o questions, Django cannot serve static files in production (when DEBUG = False
) and they have to be served by a web server. Yet, when I run my code my static files are showing up just fine even with debug turned off. This concerns because as we move to production, I can't imagine it will continue to serve those files without me setting it up so they're served by a web server and I don't want my dev environment to not give me an accurate picture of how it will work in production.
How is it possible that my app is serving static files without a web server with DEBUG = False
? I've included the relevant blurbs in my settings.py
file, urls.py
file, and my command to collectstatic
in my Dockerfile. It also serves the static files just fine when I have RUN python manage.py collectstatic
and STATIC_ROOT
commented out.
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STAT)
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.py
STAT = os.path.join(BASE_DIR, 'static')
DEBUG = False
STATIC_URL = '/static/'
STATICFILES_DIRS = [STAT]
STATIC_ROOT = os.path.join(BASE_DIR, 'prod_static')
Dockerfile
RUN python manage.py collectstatic --noinput
Upvotes: 1
Views: 162
Reputation: 66
Django is serving all contents of 'static' folder because of this definition:
] + static(settings.STATIC_URL, document_root=settings.STAT)
The command collectstatic
does not need this definition, as it searches for all folders present in STATICFILES_DIRS
and copies all static assets to your STATIC_ROOT
.
Also, you should change this:
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STAT)
Like this, on development you are serving static
folder with django and on production you will need a web server to serve prod_static
folder.
Upvotes: 2