-->

Gunicorn with Django giving a problem with static

2020-08-01 06:57发布

问题:

Got a Django project named django_server. When I run

python manage.py runserver

the page shows up as expected

Then, if I run

gunicorn django_server.wsgi:application --bind 0.0.0.0:8000

The page shows without styling

Checking the console, can see the following errors for both .css and .js files

The resource from “http://0.0.0.0:8000/static/....css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).

In the terminal where the gunicorn command was executed, can read

NOT FOUND: /static/rest_framework/css/bootstrap.min.css
NOT FOUND: /static/rest_framework/css/bootstrap-tweaks.min.css
...

In settings.py I mention

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')

This is the folder structure

Checked the permissions in static folder (ls -l)and they show as

drwxrwxr-x 4 tiago tiago 4096 jun 2 15:49 static

Checking the permissions in the files where the problem happens and

Added also to settings.py

import mimetypes

mimetypes.add_type("text/css",".css",True)
mimetypes.add_type("text/javascript",".js",True)

But the error remains.

回答1:

You need to run python manage.py collectstatic.


On your settings.py I recommend you to use whitenoise to serve your files.


1) pip install whitenoise


2) Add STATICFILES_STORAGE on settings.py

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'


3) Add to your MIDDLEWARE on settings.py

`MIDDLEWARE = [

  'whitenoise.middleware.WhiteNoiseMiddleware',

  'django.middleware.security.SecurityMiddleware',
  ...

]