Python 将 Django 应用程序部署到 Heroku 时收集静态错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36665889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Collectstatic error while deploying Django app to Heroku
提问by Stefano De Rosso
I'm trying to deploy a Django app to Heroku, it starts to build, download and installs everything, but that's what I get when it comes to collecting static files
我正在尝试将 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.
This is the whole settings.py file
这是整个 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 = '[email protected]' #my gmail username
DEFAULT_FROM_EMAIL = '[email protected]'
SERVER_EMAIL = '[email protected]'
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.clickHymaning.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'
This is the structure of the project
这是项目的结构
blog-project -- blog -- migrations
-- static
-- templates
-- blogproject
-- blogprojectenv
-- custom_user
-- media
-- .git
Any thoughts?
有什么想法吗?
回答by tomcounsell
I just updated to Django 1.10 today and had the exact same problem. Your static settings are identical to mine as well.
我今天刚刚更新到 Django 1.10 并且遇到了完全相同的问题。您的静态设置也与我的相同。
This worked for me, run the following commands:
这对我有用,运行以下命令:
disable the collectstatic during a deploy
heroku config:set DISABLE_COLLECTSTATIC=1
deploy
git push heroku master
run migrations (django 1.10 added at least one)
heroku run python manage.py migrate
run collectstatic using bower
heroku run 'bower install --config.interactive=false;grunt prep;python manage.py collectstatic --noinput'
enable collecstatic for future deploys
heroku config:unset DISABLE_COLLECTSTATIC
try it on your own (optional)
heroku run python manage.py collectstatic
在部署期间禁用 collectstatic
heroku config:set DISABLE_COLLECTSTATIC=1
部署
git push heroku master
运行迁移(django 1.10 至少添加了一个)
heroku run python manage.py migrate
使用 bower 运行 collectstatic
heroku run 'bower install --config.interactive=false;grunt prep;python manage.py collectstatic --noinput'
为未来的部署启用集合
heroku config:unset DISABLE_COLLECTSTATIC
自己尝试(可选)
heroku run python manage.py collectstatic
future deploys should work as normal from now on
从现在开始,未来的部署应该可以正常工作
回答by D. Evans
You have STATICFILES_DIRS
configured to expect a static
directory in the same directory as your settings.py
file, so make sure it's there not somewhere else.
您已STATICFILES_DIRS
配置为期望static
在与您的settings.py
文件相同的目录中有一个目录,因此请确保它不在其他地方。
Also, do you have any files in that static
directory? If you don't then git won't track it and so although it exists locally it won't exist in git. The usual solution to this is to create an empty file called .keep
in the directory which will ensure that git tracks it. But once you have some static files in this directory then it won't be a problem anymore.
另外,你那个static
目录下有文件吗?如果不这样做,则 git 将不会跟踪它,因此尽管它存在于本地,但它不会存在于 git 中。通常的解决方案是创建一个.keep
在目录中调用的空文件,以确保 git 跟踪它。但是一旦你在这个目录中有一些静态文件,那么它就不再是问题了。
回答by citynorman
Run python manage.py collectstatic
locally and fix any errors. In my case there were reference errors that prevented that command from running successfully.
在python manage.py collectstatic
本地运行并修复任何错误。就我而言,存在阻止该命令成功运行的引用错误。
回答by Diego Santa Cruz Mendezú
This worked for me:
这对我有用:
step 1 - heroku config:set DISABLE_COLLECTSTATIC=1
step 2 - git push heroku master
步骤 1 -heroku config:set DISABLE_COLLECTSTATIC=1
步骤 2 -git push heroku master
回答by Harry Moreno
Heroku had made a document with suggestions on how to handle this https://devcenter.heroku.com/articles/django-assets
Heroku 已经制作了一份文档,其中包含有关如何处理此https://devcenter.heroku.com/articles/django-assets 的建议
add to settings.py
添加到 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'),
)
make a directory in the root of your project called staticfiles
, put a favicon or something in there, just make sure git tracks it. Then the collectstatic command should finish on heroku.
在项目的根目录中创建一个名为 的目录,在其中staticfiles
放置一个图标或其他东西,只需确保 git 跟踪它。然后 collectstatic 命令应该在 heroku 上完成。
回答by awwester
It seems to me that it's having problems creating that blogproject/static
folder. I see you have a static folder inside your blog app, but it should be up one level in your blogproject folder.
在我看来,它在创建该blogproject/static
文件夹时遇到了问题。我看到您的博客应用程序中有一个静态文件夹,但它应该在您的 blogproject 文件夹中上一级。
Try creating a static
folder inside your blogproject
folder and that error should go away.
尝试static
在您的blogproject
文件夹中创建一个文件夹,该错误应该会消失。
回答by digitalindustrialist
Today, not all of the requirements came in properly with $ pipenv install django
from the heroku-django-template and $ pip install -r requirements.txt
.
今天,并非所有要求都$ pipenv install django
来自 heroku-django-template 和$ pip install -r requirements.txt
.
The latest version of the template includes a /static
folder with a humans.txt
, so the previous solution is likely not the proplem
模板的最新版本包含一个/static
带有的文件夹humans.txt
,因此以前的解决方案可能不是问题
Try running $ pipenv install whitenoise
and then $ pip freeze > requirements.txt
.
尝试运行$ pipenv install whitenoise
,然后$ pip freeze > requirements.txt
。
If that works, I would recommend $ pip install psycopg2 --ignore-installed
and $ pip freeze > requirements.txt
as well, otherwise you will similarly have problems migrating.
如果可行,我会推荐$ pip install psycopg2 --ignore-installed
并且$ pip freeze > requirements.txt
也如此,否则您将同样遇到迁移问题。
回答by Overdrivr
DO NOT disable collectstatic
on heroku with heroku config:set DISABLE_COLLECTSTATIC=1
. This will just hide the error and not make your app healthy.
不要collectstatic
在 heroku 上使用heroku config:set DISABLE_COLLECTSTATIC=1
. 这只会隐藏错误,而不会使您的应用程序健康。
Instead, it's better to understand why the collectstatic command fails because it means something is not right with your settings.
相反,最好了解 collectstatic 命令失败的原因,因为这意味着您的设置有问题。
Step 1
第1步
Run locally both commands:
在本地运行这两个命令:
python manage.py collectstatic
python manage.py test
You should see one or more error messages. Most of the time, it's a missing variable (for ex: STATIC_ROOT
) you must add to your project settings.py
file.
您应该会看到一条或多条错误消息。大多数情况下,它是一个缺失的变量(例如:),STATIC_ROOT
您必须将其添加到您的项目settings.py
文件中。
It's necessary to add the test
command because some collectstatic
related issues will only surface with test
, such as this one
有必要添加test
命令,因为一些collectstatic
相关的问题只会出现在test
,比如这个
Step 2
第2步
Once you've fixed all the error messages locally, push again to heroku.
在本地修复所有错误消息后,再次推送到 heroku。
Troubleshooting
故障排除
Remember you can also run commands directly in your heroku VM. If you cannot reproduce locally, run the collecstatic command in heroku and check what's going on directly in your production environment:
请记住,您也可以直接在 heroku VM 中运行命令。如果您无法在本地重现,请在 heroku 中运行 colecstatic 命令并直接检查您的生产环境中发生了什么:
python manage.py collectstatic --dry-run --noinput
(Same goes for heroku console obviously)
(显然,heroku 控制台也是如此)