将Django应用程序部署到Heroku时出现Collectstatic错误

时间:2016-04-16 15:14:47

标签: python django heroku deployment collectstatic

我正在尝试将一个Django应用程序部署到Heroku,它开始构建,下载和安装所有内容,但这就是我在收集静态文件时所获得的

$ python manage.py collectstatic --noinput
remote:        Traceback (most recent call last):
remote:          File "manage.py", line 10, in <module>
remote:            execute_from_command_line(sys.argv)
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
remote:            utility.execute()
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
remote:            self.fetch_command(subcommand).run_from_argv(self.argv)
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
remote:            self.execute(*args, **cmd_options)
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
remote:            output = self.handle(*args, **options)
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 168, in handle
remote:            collected = self.collect()
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 98, in collect
remote:            for path, storage in finder.list(self.ignore_patterns):
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/finders.py", line 112, in list
remote:            for path in utils.get_files(storage, ignore_patterns):
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/utils.py", line 28, in get_files
remote:            directories, files = storage.listdir(location)
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/core/files/storage.py", line 300, in listdir
remote:            for entry in os.listdir(path):
remote:        OSError: [Errno 2] No such file or directory: '/app/blogproject/static'
remote: 
remote:  !     Error while running '$ python manage.py collectstatic --noinput'.
remote:        See traceback above for details.
remote: 
remote:        You may need to update application code to resolve this error.
remote:        Or, you can disable collectstatic for this application:
remote: 
remote:           $ heroku config:set DISABLE_COLLECTSTATIC=1
remote: 
remote:        https://devcenter.heroku.com/articles/django-assets
remote: 
remote:  !     Push rejected, failed to compile Python app
remote: 
remote: Verifying deploy...
remote: 
remote: !   Push rejected to pin-a-voyage.

这是整个settings.py文件

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import dj_database_url

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



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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*********************'

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


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
    'custom_user',
    'django_markdown',
    'parsley',
)

#### AUTH ###

AUTH_USER_MODEL = 'custom_user.CustomUser'

AUTHENTICATION_BACKENDS = (
    'custom_user.backends.CustomUserAuth',
    'django.contrib.auth.backends.ModelBackend',
    # 'django.contrib.auth.backends.RemoteUserBackend',
)

#############

#### EMAIL ###

EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_PASSWORD = '***' #my gmail password
EMAIL_HOST_USER = 'voyage.pin@gmail.com' #my gmail username
DEFAULT_FROM_EMAIL = 'voyage.pin@gmail.com'
SERVER_EMAIL = 'voyage.pin@gmail.com'
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

##############

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'blogproject.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 = 'blogproject.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'blogproject',
        'USER': '***',
        'PASSWORD': '***',
        'HOST': 'localhost',
        'PORT': '',
    }
}


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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Allow all host headers
ALLOWED_HOSTS = ['*']

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

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.django.GzipManifestStaticFilesStorage'

这是项目的结构

blog-project -- blog -- migrations
                     -- static
                     -- templates
             -- blogproject
             -- blogprojectenv
             -- custom_user
             -- media
             -- .git

有什么想法吗?

17 个答案:

答案 0 :(得分:34)

我刚刚更新到Django 1.10并遇到了完全相同的问题。 您的静态设置也与我的相同。

这对我有用,运行以​​下命令:

  1. 在部署期间禁用collectstatic

    heroku config:set DISABLE_COLLECTSTATIC=1

  2. 部署

    git push heroku master

  3. 运行迁移(django 1.10至少添加了一个)

    heroku run python manage.py migrate

  4. 使用bower运行collectstatic

    heroku run 'bower install --config.interactive=false;grunt prep;python manage.py collectstatic --noinput'

  5. 启用collecstatic以供将来部署

    heroku config:unset DISABLE_COLLECTSTATIC

  6. 自己尝试(可选)

    heroku run python manage.py collectstatic

  7. 未来的部署应该从现在起正常工作

答案 1 :(得分:23)

您已将STATICFILES_DIRS配置为期望与static文件位于同一目录中的settings.py目录,因此请确保该目录不在其他位置。

此外,您在static目录中是否有任何文件?如果你不这样做,那么git将不会跟踪它,所以虽然它本地存在但它不会存在于git中。通常的解决方案是在目录中创建一个名为.keep的空文件,以确保git跟踪它。但是,一旦你在这个目录中有一些静态文件,它就不再是问题了。

答案 2 :(得分:6)

请勿使用collectstatic在heroku上禁用heroku config:set DISABLE_COLLECTSTATIC=1。这只会隐藏错误,并不会使您的应用运行状况良好。

相反,最好理解为什么collectstatic命令失败,因为这意味着您的设置不正确。

步骤1

在本地运行这两个命令:

python manage.py collectstatic
python manage.py test

您应该看到一个或多个错误消息。在大多数情况下,它是一个缺失的变量(例如STATIC_ROOT),您必须将其添加到项目settings.py文件中。

有必要添加test命令,因为某些与collectstatic相关的问题只会出现在test上,例如this one

步骤2

在本地修复所有错误消息后,请再次推送到heroku。

问题排查

请记住,您也可以直接在heroku VM中运行命令。 如果您无法在本地复制,请在heroku中运行collecstatic命令,然后直接检查生产环境中发生了什么:

python manage.py collectstatic --dry-run --noinput

Launch heroku VM

(显然,heroku控制台也是如此)

答案 3 :(得分:3)

在本地运行python manage.py collectstatic并修复任何错误。在我的情况下,有一些引用错误阻止该命令成功运行。

答案 4 :(得分:2)

我遇到同样的问题。

执行此步骤

  1. heroku config:set DISABLE_COLLECTSTATIC=1
  2. git push heroku master
  3. python manage.py collectstatic
  4. python manage.py test
  5. 如果在运行测试后发生任何错误,请检查 STATIC_ROOT是正确的,例如==> STATIC_ROOT = os.path.join(BASE_DIR, 'static')
  6. 运行collectstatic命令后,检查所有静态文件是否 存储在您的根目录的 static 目录中。级别(manage.py 目录级别)...
  7. heroku run python manage.py collectstatic
  8. heroku run python manage.py migrate
  9. heroku config:unset DISABLE_COLLECTSTATIC(供将来使用)。

答案 5 :(得分:1)

在我看来,它在创建blogproject/static文件夹时遇到了问题。我看到你的博客应用程序中有一个静态文件夹,但它应该在你的blogproject文件夹中有一个级别。

尝试在static文件夹中创建blogproject文件夹,该错误应该消失。

答案 6 :(得分:1)

这对我有用:

heroku config:set DISABLE_COLLECSTATIC=1

及之后:

git push heroku master

答案 7 :(得分:1)

Heroku编写了一份文档,其中提出了有关如何处理此https://devcenter.heroku.com/articles/django-assets

的建议

添加到settings.py

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

在项目的根目录中创建一个名为staticfiles的目录,在其中放置收藏夹图标或其他内容,只需确保git跟踪它即可。然后collectstatic命令应该在heroku上完成。

答案 8 :(得分:1)

尝试再次部署应用后遇到了该问题。指定这些命令后问题就解决了:

$ heroku config:set SECRET_KEY="*secret_key*"
$ heroku config:set DEBUG_VALUE="True"
$ heroku config:set EMAIL_USER="*user-email*"
$ heroku config:set EMAIL_PASS="*pass*"

settings.py 中的这些变量是用本地环境变量调用的, heroku 在其环境中没有,因此出现错误。

答案 9 :(得分:1)

  • 发生此错误是因为您没有 staticfiles 您项目的根目录。

  • 别担心。解决方案是简单

  • 您只需要两个步骤

第 1 步:打开您的 settings.py 文件并写入

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

STATIC_ROOT = BASE_DIR / 'staticfiles'

第 2 步: 在项目根目录中的终端中运行以下给定命令。 (如果您正在为 Django 项目使用任何虚拟环境,请进入您的虚拟环境,然后进入项目的根目录,然后在给定的命令下运行。)

python manage.py collectstatic

恭喜:您的问题已解决。

现在,您可以提交推送您的“更改”,使其反映在您的存储库中,然后您就可以开始了。

答案 10 :(得分:0)

出现这个问题是因为 Heroku 尝试运行 manage.py。 执行 manage.py 时 我们必须这样写 python manage.py 'some_command'

但 Heroku 尝试将其作为 python manage.py --noinput

因此,在这种情况下,我们可以对 manage.py 文件进行更改: 最初它看起来像这样:

 #!/usr/bin/env python
 """Django's command-line utility for administrative tasks."""
 import os
 import sys

 def main():
     """Run administrative tasks."""
     os.environ.setdefault('DJANGO_SETTINGS_MODULE', 
'your_project.settings')
     try:
         from django.core.management import execute_from_command_line
     except ImportError as exc:
         raise ImportError(
             "Couldn't import Django. Are you sure it's installed and "
             "available on your PYTHONPATH environment variable? Did you "
             "forget to activate a virtual environment?"
         ) from exc

     execute_from_command_line(sys.argv) # just put this in try block

 if __name__ == '__main__':
     main()

因此我们将 main.py 更改为:

 #!/usr/bin/env python
 """Django's command-line utility for administrative tasks."""
 import os
 import sys

 def main():
     """Run administrative tasks."""
     os.environ.setdefault('DJANGO_SETTINGS_MODULE', 
'your_project.settings')
     try:
         from django.core.management import execute_from_command_line
     except ImportError as exc:
         raise ImportError(
             "Couldn't import Django. Are you sure it's installed and "
             "available on your PYTHONPATH environment variable? Did you "
             "forget to activate a virtual environment?"
         ) from exc
     try:
          execute_from_command_line(sys.argv) # just put this in try block
     except:
          pass

 if __name__ == '__main__':
     main()

答案 11 :(得分:0)

heroku config:set DISABLE_COLLECTSTATIC=1 --app #yourappname

直接运行命令

答案 12 :(得分:0)

删除 STATICFILES_DIRS 在我的情况下有效

答案 13 :(得分:0)

就我而言,这是一个几乎如上所述的错误,在导致错误的推送之后,我设置了 SECRET_KEY "heroku config:set SECRET_KEY='*************************'"git push heroku main(再次) , heroku run python manage.py migrate , heroku run python manage.py createsuperuser .. 和一切 , heroku open 它奏效了:)

答案 14 :(得分:0)

将这行代码插入到您的 setting.py 文件中。

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

答案 15 :(得分:0)

在部署我的应用程序时,我遇到了同样的问题。我意识到我已经更新了pip版本,安装了几个插件,但是忘记创建一个新的requirements.txt文件。

在终端中运行pip freeze > requirements.txt
运行python manage.py collectstatic
现在将代码推送到github并部署到heroku服务器

希望是这样的话

答案 16 :(得分:0)

今天,并非所有要求都来自heroku-django-template和$ pipenv install django的{​​{1}}。

该模板的最新版本包含一个$ pip install -r requirements.txt文件夹,其中/static,所以以前的解决方案可能不是问题

尝试运行humans.txt,然后$ pipenv install whitenoise

如果可以,我会推荐$ pip freeze > requirements.txt$ pip install psycopg2 --ignore-installed,否则您同样会遇到迁移问题。

相关问题