Search code examples
cssdjangoapachemime

Django css and javascript app not served in production


I have a django project which in development mode css are loaded just fine but not in production.

In my settings.py file I've set these trhee variables

STATIC_ROOT = BASE_DIR / 'staticfiles/'
STATIC_URL = 'static/'
STATICFILES_DIRS = [BASE_DIR / 'static',]

I also set DEBUG = False

When I run python manage.py collectstatic command the staticfiles folder receives the files properly. I created a static folder in the root of the project to install bootstrap there, again, in developent runs just fine. I'm using Apache server throug XAMPP becasuse I'm on Windows. the configuration for the project is next:

LoadFile "C:/Python310/python310.dll"
LoadModule wsgi_module "C:/Users/life/.virtualenvs/outgoing-qJCH8A9k/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd"
WSGIPythonHome "C:/Users/life/.virtualenvs/outgoing-qJCH8A9k"

WSGIScriptAlias /outgoing "D:/DEV/PYTHON/GASTOS/software/outgoing/project/wsgi.py" application-group=%{GLOBAL}
WSGIPythonPath "D:/DEV/PYTHON/GASTOS/software/outgoing"

<Directory "D:/DEV/PYTHON/GASTOS/software/outgoing/project">
<Files wsgi.py>
Require all granted
</Files>
</Directory>

Alias /static/ "D:/DEV/PYTHON/GASTOS/software/outgoing/staticfiles/"

<Directory "D:/DEV/PYTHON/GASTOS/software/outgoing/staticfiles">
Require all granted
</Directory>`

The point is, the app load well but without the bootstrap css and javascript files. Also the browser console tells this.

Refused to apply style from 'http://localhost/outgoing/static/node_modules/bootstrap/dist/css/bootstrap.min.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

GET http://localhost/outgoing/static/node_modules/bootstrap/dist/js/bootstrap.bundle.min.js

Help please.


Solution

  • If your are in a production Environment, it's recommended to use Django's WhiteNoise library which is one of the easiest methods for serving static Files/assets directly in production.

    pip install whitenoise
    

    In your settings.py

    MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware', 
    ......,
    ]
    # 
    STATIC_ROOT = BASE_DIR / 'staticfiles'
    STATIC_URL = '/static/'
    #
    

    Optionally, you can reduce the size of the static files when they are served (this is more efficient). Just add the following to the bottom of settings.py:

    STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
    

    Depnding on your production server you can collectstatic by:

    python manage.py collectstatic