【问题标题】:Heroku Internal Server Error when Debug is False and collectstatic dosen't work - Django当 Debug 为 False 并且 collectstatic 不起作用时 Heroku 内部服务器错误 - Django
【发布时间】:2020-12-18 10:04:30
【问题描述】:

我在 Heroku 上部署了一个使用 Postgres 的应用程序。 每当我将 Debug 设置为 True 时,它​​都可以正常工作。当我将其设置回 False 时,它​​会给出错误 500,内部服务器错误。我不知道为什么会这样。 它与静态文件有关吗? 我正在使用白噪声来提供静态文件。

任何时候我运行heroku run python manage.py collectstatic,它都会给我

Running python manage.py collectstatic on djangotestapp... up, run.9614 (Free)

300 static files copied to '/app/staticfiles', 758 post-processed.

当我运行heroku run bash 时,我发现没有staticfiles 文件夹。 它究竟将静态文件复制到哪里? 这是导致错误 500 的原因吗? 我该如何解决?

settings.py


import os
import dj_database_url
from decouple import config, Csv

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


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', cast=bool)

SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 200
SECURE_HSTS_PRELOAD = True

ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast =Csv())

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',

    # Third-party
    'allauth',
    'allauth.account',
    'crispy_forms',
    'widget_tweaks',
    'debug_toolbar',
    'phonenumber_field',
    'django_datatables_view',
    
    'whitenoise.runserver_nostatic',     

    # Local
    'users',
    'pages',
    'attendance',
]

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

ROOT_URLCONF = 'djangotestapp_project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        #'DIRS': ['templates'],
        'DIRS': [os.path.join(BASE_DIR, '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 = 'djangotestapp_project.wsgi.application'

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': config('DB_NAME'),
        'USER':  config('DB_USER'),
        'PASSWORD': config('DB_PASSWORD'),
        'HOST':  config('DB_HOST'),
        'PORT': '5432',
    },  
}

prod_db = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(prod_db)

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'

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

#STATICFILES_FINDERS = [    
#    'django.contrib.staticfiles.finders.FileSystemFinder',
#    'django.contrib.staticfiles.finders.AppDirectoriesFinder',    
#]


#STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
#
# STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'

AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
)

更新 我运行heroku logs -tail -a djangotestapp 来查看发生的错误,这就是它给我的。

2020-08-30T20:23:20.090560+00:00 app[web.1]: raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name)
2020-08-30T20:23:20.090560+00:00 app[web.1]: ValueError: Missing staticfiles manifest entry for 'css/font-rules-roboto.css'

文件 font-rules-roboto.css 让我能够在没有任何 Google 字体 API 链接的情况下使用roboto 字体。

我已经运行python manage.py collectstatic,但它什么也没做。

【问题讨论】:

    标签: python django heroku


    【解决方案1】:

    我认为您的问题与您的ALLOWED_HOSTS 有关。当您关闭 Django 设置的调试模式时,您必须将您的项目主机 IP 或域添加到 ALLOWED_HOSTS。因此,我认为将主机服务器的 IP 添加到您的 .env 文件中,如 (ALLOWED_HOSTS = localhost, ..., IP.OF.YOUR.HOST) 将解决您的问题。

    【讨论】:

    • 为了测试目的,看看这个问题是否来自这部分,将ALLOWED_HOSTS更改为ALLOWED_HOSTS = '*'(允许所有主机访问您的服务器)并重新加载您的页面,看看它是否是工作与否。
    • 注意:为了安全起见,测试后不要忘记将ALLOWED_HOSTS更改为默认设置。
    • 请将您项目的settings.py中的ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast =Csv())行改为ALLOWED_HOSTS = ['*'],看看错误代码是否从500变为404并告诉我结果。
    • 也许https://stackoverflow.com/questions/50658241/django-doesnt-load-static-files-valueerrormissing-staticfiles-manifest-entry可以帮助你。
    • 谢谢,这个链接帮了很多忙。我通过添加步骤解决了它。请检查答案。
    【解决方案2】:

    感谢@Roham 的帮助。我通过添加步骤解决了它。

    在我评论之后 STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage',网站开始工作了,但是静态文件没有加载。

    然后我将此行添加到设置中,WHITENOISE_USE_FINDERS = True。 它使您的应用无需收集静态文件即可运行。

    在我这样做之后,所有的静态文件加载没有任何问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-05
      • 1970-01-01
      • 2020-09-03
      • 2018-01-05
      • 2018-03-20
      • 2018-09-26
      • 2021-05-10
      • 2019-09-21
      相关资源
      最近更新 更多