70

我正在尝试将 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

有什么想法吗?

4

19 回答 19

90

我今天刚刚更新到 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. 使用凉亭运行 collectstatic

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

  5. 为未来的部署启用集体静态

    heroku config:unset DISABLE_COLLECTSTATIC

  6. 自己尝试(可选)

    heroku run python manage.py collectstatic

从现在开始,未来的部署应该正常工作

于 2016-08-15T11:59:28.957 回答
39

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

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

于 2016-04-17T13:09:48.880 回答
15

不要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,例如这个

第2步

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

故障排除

请记住,您也可以直接在 heroku VM 中运行命令。如果您无法在本地重现,请在 heroku 中运行 collectstatic 命令并直接检查您的生产环境中发生了什么:

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

启动 heroku 虚拟机

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

于 2020-05-02T16:47:41.057 回答
7

在本地运行python manage.py collectstatic并修复任何错误。在我的情况下,存在阻止该命令成功运行的参考错误。

于 2017-12-21T19:58:36.807 回答
6
  • 发生此错误是因为您的项目的根目录中没有静态文件。

  • 不用担心。解决方案很简单

  • 你只需要两个步骤

第 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

恭喜:您的问题已解决。

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

于 2021-06-17T21:25:22.183 回答
4

我面临同样的问题..

按照这个步骤

  1. heroku 配置:设置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 命令后,检查所有静态文件都存储在根目录的静态目录中。级别(manage.py 目录级别)...
  7. heroku run python manage.py collectstatic.
  8. heroku run python manage.py migrate
  9. heroku config:unset DISABLE_COLLECTSTATIC(供将来使用)。
于 2020-09-11T17:45:06.903 回答
4

这对我有用:

第 1heroku config:set DISABLE_COLLECTSTATIC=1
步 - 第 2 步 -git push heroku master

于 2018-07-25T04:16:43.180 回答
3

如果你使用django-heroku

也许您忘记将此设置放在行文本 settings.py 的底部,以便可以读取所有配置参数

import django_heroku

django_heroku.settings(locals())

就像文档一样:

Django-Heroku 的使用

settings.py, 在最底部::

…
# Configure Django App for Heroku.
import django_heroku
django_heroku.settings(locals())

这将自动为您的应用程序配置DATABASE_URLALLOWED_HOSTS、 WhiteNoise(用于静态资产)、Logging 和 Heroku CI。

ps:对不起我的英语不好

于 2021-08-19T05:33:29.427 回答
2

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放置一个 favicon 或其他东西,只要确保 git 跟踪它即可。然后 collectstatic 命令应该在 heroku 上完成。

于 2019-01-24T22:11:44.223 回答
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 在其环境中没有这些变量,因此出现了错误。

于 2021-07-09T08:12:38.003 回答
0

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

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

于 2021-02-28T10:53:47.127 回答
0

删除 STATICFILES_DIRS 在我的情况下有效

于 2021-05-31T07:02:48.140 回答
0

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

static尝试在您的文件夹中创建一个文件blogproject夹,该错误应该会消失。

于 2016-04-16T16:02:27.583 回答
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()
于 2021-07-19T05:17:35.017 回答
0

今天,并不是所有的需求都$ pipenv install django来自 heroku-django-template 和$ pip install -r requirements.txt.

最新版本的模板包含一个/static带有 的文件夹humans.txt,因此以前的解决方案可能不是问题

尝试运行$ pipenv install whitenoise,然后$ pip freeze > requirements.txt.

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

于 2018-01-06T18:07:34.483 回答
0

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

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

如果是这样的话,希望这会有所帮助

于 2020-08-18T19:15:22.917 回答
0
heroku config:set DISABLE_COLLECTSTATIC=1 --app #yourappname

只需运行命令

于 2021-06-04T13:00:39.030 回答
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 它工作了:)

于 2021-05-25T06:24:34.323 回答
0

如果您使用.env文件,python-decouple则必须在Heroku app settings > Config Vars. 否则collectstatic行不通。

于 2021-09-06T11:09:19.603 回答