带有 Django 的 Gunicorn 给静态文件带来了问题

Gunicorn with Django giving a problem with static files

获得了一个名为 django_server 的 Django 项目。当我运行

python manage.py runserver

页面按预期显示

那么,如果我运行

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

显示的页面没有样式

检查控制台,可以看到 .css 和 .js 文件都出现以下错误

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).

在执行gunicorn命令的终端,可以读到

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

在settings.py我提到

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

这是文件夹结构

检查了静态文件夹 (ls -l) 中的权限,它们显示为

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

检查出现问题的文件的权限和

也添加到 settings.py

import mimetypes

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

但错误依旧。

您需要 运行 python manage.py collectstatic.


在您的 settings.py 上,我建议您使用 whitenoise 来提供您的文件。


1) pip install whitenoise


2) 在 settings.py

上添加 STATICFILES_STORAGE

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'


3) 添加到 settings.py

上的 MIDDLEWARE
`MIDDLEWARE = [

  'whitenoise.middleware.WhiteNoiseMiddleware',

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

]