Home > other >  Why can't I serve my static files to Django?
Why can't I serve my static files to Django?

Time:11-22

Before anyone marks this as a duplicate I have seen all of the other questions on similar topics and tried all of the solutions without effect.

My Django application is small and I am happy to serve the static files from the same server

In settings.py I have

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

I have uploaded my application to the server and run

python.manage.py collectstatic

All of my static files are in the appropriate directories under staticfiles

project-root
├── staticfiles
│   ├── css
│   │   ├── base.css
│   ├── js
│   │   ├── common.js

In my html I have

{% load static %}
<link href="{% static 'css/base.css' %}" rel="stylesheet">

On loading the page I get the error

Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

I think this is because it cannot filed the css file

Where am I going wrong? Do I need to provide any more information?

CodePudding user response:

project_name - app_name - static - app_name - css/js file

<link rel="stylesheet" href="{% static 'app_name/style.css' %}">

CodePudding user response:

My problem has been solved by installing the whitenoise package. (I have not seen this recommended on the responses to similar questions around this problem)

pip install whitenoise

And add it to the middleware section of settings.py

MIDDLEWARE = [
    ...
    'whitenoise.middleware.WhiteNoiseMiddleware', 
    ...
]

All of my static files are now loaded and the site works perfectly with no further configuration

(I am assuming that the problem might have been caused by a quirk in the site's host's server settings.)

  • Related