Django Whitenoise 导致收集静态错误

Django Whitenoise causes error collecting static

当我 运行 在我的 Django 站点上收集静态信息时,我总是会收到错误消息。

这是我的 settings.py:

"""
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 3.1.1.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIRS = os.path.join(BASE_DIR, 'templates')

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), )


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'not showing it here'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'news',
    'writers',
]
INSTALLED_APPS += ('django_summernote', )

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'news.middleware.TimezoneMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATES_DIRS],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'news.context_processors.common_variables'
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'

X_FRAME_OPTIONS = 'SAMEORIGIN'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

当我 运行 collectstatic 我得到:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\core\management\__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\core\management\__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\core\management\base.py", line 330, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\core\management\base.py", line 371, in execute
    output = self.handle(*args, **options)
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\management\commands\collectstatic.py", line 194, in han
dle
    collected = self.collect()
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\management\commands\collectstatic.py", line 132, in col
lect
    for original_path, processed_path, processed in processor:
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\wh
itenoise\storage.py", line 148, in post_process_with_compression
    for name, hashed_name, processed in files:
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\wh
itenoise\storage.py", line 88, in post_process
    for name, hashed_name, processed in files:
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\storage.py", line 399, in post_process
    yield from super().post_process(*args, **kwargs)
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\storage.py", line 231, in post_process
    for name, hashed_name, processed, _ in self._post_process(paths, adjustable_
paths, hashed_files):
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\storage.py", line 288, in _post_process
    content = pattern.sub(converter, content)
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\storage.py", line 187, in converter
    hashed_url = self._url(
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\storage.py", line 126, in _url
    hashed_name = hashed_name_func(*args)
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\storage.py", line 338, in _stored_name
    cache_name = self.clean_name(self.hashed_name(name))
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\wh
itenoise\storage.py", line 166, in hashed_name
    name = super(CompressedManifestStaticFilesStorage, self).hashed_name(
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\storage.py", line 87, in hashed_name
    if not self.exists(filename):
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\core\files\storage.py", line 311, in exists
    return os.path.exists(self.path(name))
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\contrib\staticfiles\storage.py", line 41, in path
    return super().path(name)
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\core\files\storage.py", line 324, in path
    return safe_join(self.location, name)
  File "C:\Users\Me\AppData\Local\Programs\Python\Python38\lib\site-packages\dj
ango\utils\_os.py", line 29, in safe_join
    raise SuspiciousFileOperation(
django.core.exceptions.SuspiciousFileOperation: The joined path (E:\Folder\WebProjects\website\mysite\img\arrow-left.png) is l
ocated outside of the base path component (E:\Folder\WebProjects\website\mysite\staticfiles)

我已经搜索过了,但找不到 E:\Folder\WebProjects\website\mysite\img\arrow-left.png

只有在我使用 Whitenoise 时才会出现这种情况。如果我使用普通的 Django 静态服务,它可以工作,但 CSS 不显示。我正在使用 Heroku

编辑:这是我的 wsgi.py

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')

application = get_wsgi_application()

在 wsgi.py 中注释 whitenoise 部分,然后 运行 在部署时收集静态信息并取消注释 whitenoise 部分。

也不需要STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage

样本 wsgi.py

import os

from django.core.wsgi import get_wsgi_application    
from whitenoise.django import DjangoWhiteNoise

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')

application = get_wsgi_application()
application = DjangoWhiteNoise(application)