Django Heroku Debug = False,静态文件导致内部服务器错误

时间:2019-02-20 06:30:03

标签: python django heroku internal-server-error

已解决: 我不确定最终要解决的问题是什么组合,但是最后一步是修复我的静态文件层次结构。以前,我只是拥有/<base>/static/main.css,但我将其更改为/<base>/static/<project-name>/main.css,并以某种方式解决了该问题。

原始问题: 我目前正在尝试使用Heroku部署Django应用。但是,当我尝试使用Debug=False进行部署时,由于服务器找不到main.css样式表,我收到内部服务器错误消息。请注意,当Debug=True时,一切正常。

当我在命令行中尝试python manage.py findstatic --verbosity 2 main.css时,出现错误消息 “找不到与'main.css'相匹配的文件。在以下位置查找:   /Users/Kyle/.local/share/virtualenvs/hostable-Ij2AFM0k/lib/python3.6/site-packages/django/contrib/admin/static”,但我不知道为什么要在这里查看。

下面,我提供了我的settings.py文件。我的文件层次结构一团糟,因为进行collectstatic会在staticfiles文件夹中生成一大堆静态文件,但是我不知道它们来自何处或目的是什么。我在static文件夹中有样式表,但这似乎不再被调用。

我想知道的是:我应该在设置或文件层次结构中进行哪些更改,以便找到main.css

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

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'crispy_forms',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'menus.apps.MenusConfig',
    'events.apps.EventsConfig',
    'users.apps.UsersConfig',
]

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 = 'project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates'),
            os.path.join(BASE_DIR, 'users/templates'),
            os.path.join(BASE_DIR, 'events/templates'),
            os.path.join(BASE_DIR, 'menus/templates'),
        ],
        '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 = 'project.wsgi.application'


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

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


# Password validation
# https://docs.djangoproject.com/en/2.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/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

DEBUG_PROPAGATE_EXCEPTIONS = True

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')

P.S。我也尝试过使用whitenoise也不成功。

我还应该提到,当我查看日志文件时,会收到http://whitenoise.evans.io/en/stable/django.html#why-do-i-get-valueerror-missing-staticfiles-manifest-entry-for此处引用的ValueError: Missing staticfiles manifest entry for …消息。

settings.py的工作版本:

DEBUG = False

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'crispy_forms',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'menus.apps.MenusConfig',
    'events.apps.EventsConfig',
    'users.apps.UsersConfig',
]

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 = 'project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates'),
            os.path.join(BASE_DIR, 'users/templates'),
            os.path.join(BASE_DIR, 'events/templates'),
            os.path.join(BASE_DIR, 'menus/templates'),
        ],
        '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 = 'project.wsgi.application'


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

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


# Password validation
# https://docs.djangoproject.com/en/2.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/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

DEBUG_PROPAGATE_EXCEPTIONS = True

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

3 个答案:

答案 0 :(得分:2)

Debug = False中,尝试在项目目录的 url.py 文件中添加静态文件的url:

from django.contrib import admin
from django.urls import path, re_path, include
from django.conf.urls.static import static
from django.conf import settings
from django.views.static import serve

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^', include('app.urls')),

    re_path(r'^static/(?P<path>.*)$', serve,
            {'document_root': settings.STATIC_ROOT}),
] 

更新

通过在项目urls.py文件中添加以上内容,Django将检查您的 STATIC_URL 设置并连接视图以相应地提供静态文件。

此外,如docs中所述,在生产模式下(即DEBUG = False),您应该使用Web服务器提供静态文件,而不是Django。因此,如果staticfilesDEBUG = False将拒绝为您的资产服务。

答案 1 :(得分:0)

基本上

WhiteNoise可与任何与WSGI兼容的应用程序一起使用,但具有一些针对Django的特殊自动配置功能。<​​/ p>

WhiteNoise为您提供最佳实践,例如:

  • 提供压缩内容(gzip和Brotli格式,处理 正确接受编码和Vary标头)
  • 在不会改变的内容上设置未来的缓存头

在settings.py

中的任意位置添加此行
 STATICFILES_STORAGE = ‘whitenoise.storage.CompressedManifestStaticFilesStorage’

答案 2 :(得分:0)

在Heroku上的应用中,我使用了https://docs.djangoproject.com/en/1.11/howto/static-files/中的说明。在settings.py中,我配置了:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/' 
STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] 
STATIC_ROOT = os.path.join(BASE_DIR, 'collectstatic') 
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

我还使用了此命令将所有文件从您的静态文件夹复制到STATIC_ROOT目录中:python manage.py collectstatic