【问题标题】:Gunicorn with Django giving a problem with static files带有 Django 的 Gunicorn 给出了静态文件的问题
【发布时间】:2020-09-21 03:36:26
【问题描述】:

有一个名为 django_server 的 Django 项目。当我跑步时

python manage.py runserver

页面按预期显示

然后,如果我运行

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

页面显示没有样式

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

资源来自 “http://0.0.0.0:8000/static/....css”被屏蔽 由于 MIME 类型(“text/html”)不匹配(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 django ubuntu gunicorn static-files


    【解决方案1】:

    你需要运行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',
      ...
    
    ]
    

    【讨论】:

    • 嗨米格尔德马托斯。我也跑了 collectstatic ,因此是静态文件夹。我会尽快结帐whitenoise 并通知您。
    猜你喜欢
    • 2012-11-20
    • 2021-01-02
    • 2017-10-27
    • 2021-05-27
    • 2020-08-08
    • 1970-01-01
    • 2016-11-24
    • 2014-09-11
    • 2013-08-12
    相关资源
    最近更新 更多