Django Debug=False whitenoise 不工作

Django Debug=False whitenoise not working

我正在尝试将我的全功能站点(当本地和 Debug=True 时)部署到 Heroku。当我使用默认的 Django staticfile_storage 设置时,我的站点显示为实时但没有任何静态文件(css、图像等)。管理面板可以使用,但也没有任何样式。

但是,当我尝试使用 Whitenoise(这正是我最初的意图)时,出现服务器 500 错误。管理面板将无法使用。我无法弄清楚我做错了什么。

我已经尝试按照 Heroku 的模板对我的 settings.py 文件进行建模: https://github.com/heroku/heroku-django-template, and Whitenoise's documentation http://whitenoise.evans.io/en/latest/django.html

当我查看最近的 Heroku 日志时,我发现

at=info method=GET path="/static/css/styles.css" host=www.mysite.net request_id=826280da-21ba-48a1-8a05-679c92871d38 dyno=web.1 connect=0ms service=3ms status=404 bytes=361

当我推送到 Heroku 时,部署成功,但是当我 运行

heroku run python3 manage.py collectstatic

它说我必须覆盖先前存在的文件 (yes/no),当我说是时,我收到一条错误消息,指出找不到 app/static 目录。

我非常困惑 - 我做错了什么?如果我的静态文件目录不正确,我该如何找到它?

项目结构

mysite/
    blog/
        static/
            css/
                styles.css
            images/
                favicon.png
        templates/
            blog/
                blog_list.html
                blog_detail.html
            index.html
            bio.html
            resume.html
        models.py
        views.py
        urls.py
    media/
        portfoliopieces/
             1.png
             2.png
             3.png
             4.png
    mysite/
        settings.py
        urls.py
        wsgi.py
    portfolio/
        templates/
            portfolio_list.html
            portfolio_detail.html
        models.py
        views.py
        urls.py

mysite/urls.py

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py

import os
from secrets import *
import dj_database_url

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

# SECURITY WARNING: keep the secret key used in production secret!
# see secrets.py

# SECURITY WARNING: don't run with debug turned on in production!
# DEBUG = bool(os.environ.get('DJANGO_DEBUG', True))
# For production, make false
DEBUG = False

ALLOWED_HOSTS = ['www.mysite.com' ]


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'whitenoise.runserver_nostatic',
    'django.contrib.staticfiles',
    'portfolio.apps.PortfolioConfig',
    'blog.apps.BlogConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    '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',
]

ROOT_URLCONF = 'mysite.urls'


WSGI_APPLICATION = 'mysite.wsgi.application'

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

# STATIC_URL = '/static/'

STATIC_DIR = os.path.join(BASE_DIR, 'static')

# STATICFILES_DIRS = [
    #os.path.join(BASE_DIR, "static"),
#]

# STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")

STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')

STATIC_URL = '/static/'

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
     os.path.join(PROJECT_ROOT, 'static'),
]

# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
# STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")

SECURE_CONTENT_TYPE_NOSNIFF = True

SECURE_BROWSER_XSS_FILTER = True

# Update database configuration with $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

在整整两天尝试让 whitenoise 工作但失败后,我想出了如何让默认的 Django 静态文件在 Heroku 上工作。这真的很棘手,这可能会对其他人有所帮助:settings.py 文件(假设我的项目结构)应该如下所示:

import os
from secrets import *
import dj_database_url

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

DEBUG = False

ALLOWED_HOSTS = ['www.mysite.com']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'portfolio.apps.PortfolioConfig',
    'blog.apps.BlogConfig',
]

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',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Heroku: Update database configuration from $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

# Static files (CSS, JavaScript, Images)

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")