在将Django应用部署到Heroku时,解决whitenoise相关错误

在像Djangogirls之类的地方,建议安装whitenoise作为在Heroku上运行Django应用所需的一个包之一。

另外,在Django项目的wsgi.py文件的最后一行中,要求添加以下内容。

from whitenoise.django import DjangoWhiteNoise


application = DjangoWhiteNoise(application)

如果在2018年8月的最新版本whitenoise 4.0上安装并进行了上述编辑,则wsgy.py将导致Django应用程序无法通过以下错误启动。

$ python manage.py runserver
()
    from whitenoise.django import DjangoWhiteNoise
  File "(略)/lib/python3.7/site-packages/whitenoise/django.py", line 2, in <module>
    '\n\n'
ImportError: 

Your WhiteNoise configuration is incompatible with WhiteNoise v4.0
This can be fixed by following the upgrade instructions at:
http://whitenoise.evans.io/en/stable/changelog.html#v4-0

()
django.core.exceptions.ImproperlyConfigured: WSGI application
 '(Djangoプロジェクト名).wsgi.application' could not be loaded; 
Error importing module.

当我查看whitenoise的django.py文件时,我发现无论我从whitenoise.django中尝试导入任何内容,都会出现一个必然抛出错误的处理过程。

raise ImportError(
        '\n\n'
        'Your WhiteNoise configuration is incompatible with WhiteNoise v4.0\n'
        'This can be fixed by following the upgrade instructions at:\n'
        'http://whitenoise.evans.io/en/stable/changelog.html#v4-0\n'
        '\n')

处理方法

使用旧版本的白噪音

只需一种选择,将已安装的whitenoise 4.0卸载。

$ pip uninstall whitenoise

我们将安装旧版的白噪声替代4.0版本,并选择了比它旧一版本的3.3.1版本。

$ pip install whitenoise == 3.3.1

不要在wsgi.py中进行编辑,而是要在settings.py中进行编辑。

据说自从4.0版本,Django对whitenoise的处理方式有所变化。

删掉了在wsgi.py的最后一行添加的以下描述。

from whitenoise.django import DjangoWhiteNoise # この行は削除する

application = DjangoWhiteNoise(application) # この行も削除する

请在settings.py文件的MIDDELWARE中添加’whitenoise.middleware.WhiteNoiseMiddleware’。

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware', # この行を追加
    'django.contrib.sessions.middleware.SessionMiddleware',
# 以下略
]

此外,根据官方网站的指示,在’django.middleware.security.SecurityMiddleware’之后和其他中间件之前进行编写,我按照这个顺序进行了操作。

bannerAds