使用Django的Gunicorn给静态文件带来了问题。

问题描述 投票:0回答:1

有一个名为django_server的Django项目。当我运行

python manage.py runserver

网页如期而至

DRF working fine

那么,如果我运行

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

页面显示无样式

Gunicorn Django without style

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

资源来自"http:/0.0.0.0:8000static...css。"由于MIME类型("texthtml")不匹配(X-Content-Type-Options:nosniff)而被阻止。

Guniorn DRF console errors在执行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')

这就是文件夹的结构

Folder structure

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

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

检查发生问题的文件中的权限,并且

Ubuntu file permissions

也添加到settings.py中

import mimetypes

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

但错误依旧。

python django ubuntu gunicorn static-files
1个回答
1
投票

你需要运行 python manage.py collectstatic.

在你的 settings.py 我建议你使用 whitenoise 以服务于你的文件。

1) pip install whitenoise

2) 添加 STATICFILES_STORAGE 在settings.py上

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

3) 添加到您的网站 MIDDLEWARE 在settings.py上

`MIDDLEWARE = [

  'whitenoise.middleware.WhiteNoiseMiddleware',

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

]
© www.soinside.com 2019 - 2024. All rights reserved.