您正在使用staticfiles应用程序,但没有将STATIC_ROOT设置为文件系统路径。

24

我已经查看了所有其他答案,但似乎没有任何一种方法适用于我。我正在按照教程尝试将我的master分支推送到Heroku,并且遇到了错误You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path。我正在使用Django 2.0和Python 3.6.3。完整的回溯信息:

remote: -----> $ python manage.py collectstatic --noinput
remote:        Traceback (most recent call last):
remote:          File "manage.py", line 15, in <module>
remote:            execute_from_command_line(sys.argv)
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
remote:            utility.execute()
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
remote:            self.fetch_command(subcommand).run_from_argv(self.argv)
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
remote:            self.execute(*args, **cmd_options)
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute
remote:            output = self.handle(*args, **options)
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle
remote:            collected = self.collect()
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect
remote:            handler(path, prefixed_path, storage)
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 344, in copy_file
remote:            if not self.delete_file(path, prefixed_path, source_storage):
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 250, in delete_file
remote:            if self.storage.exists(prefixed_path):
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 308, in exists
remote:            return os.path.exists(self.path(name))
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 43, in path
remote:            raise ImproperlyConfigured("You're using the staticfiles app "
remote:        django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.
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:  !     Push rejected, failed to compile Python app.
remote: 
remote:  !     Push failed
remote: Verifying deploy...
remote: 
remote: !   Push rejected to obscure-spire-97107.
remote: 
To https://git.heroku.com/obscure-spire-97107.git
 ! [remote rejected] master -> master (pre-receive hook declined)

我的settings.py

import os

# 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.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '5af%uw_wn*o#v$gp!dj1yrxf0#z+4_+&4$3f^kjh*fc7+ec4*9'

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

ALLOWED_HOSTS = []


# Application definition

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

    #added apps for project, my_apps
    'blog',
    'users',

    #third party apps
    'bootstrap3',

]

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


# Database
# https://docs.djangoproject.com/en/2.0/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.0/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.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'

#My settings
LOGIN_URL = 'users/login/'

#settings bootstrap3
BOOTSTRAP3 = {
    'include_jquery':True,
}

#Heroku settings
# ROOT_PATH = os.path.dirname(__file__)
if os.getcwd() == '/app':
    import dj_database_url
    DATABASES = {
        'default': dj_database_url.config(default='postgres://localhost')
    }

    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

    ALLOWED_HOSTS = ['*']

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

我尝试去掉if语句,看看是否是问题所在,但没有成功。希望能得到任何建议。


6
可能现在这个问题已经不相关了,但你刚才分享了一个秘密密钥,这是一个不好的做法。作为新的 SO 用户的示例,你可以用“*****”代替秘密密钥。 - Anders_K
4个回答

27

总结ratrace的回答,主要解决方案是添加

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

要到 settings.py 文件中进行设置。其中STATIC_ROOT 是静态文件复制的目标路径,也是在部署Django应用程序时提供静态文件服务的来源。


如果你运行 "python manage.py collectstatic",如果该文件夹不存在,将会在 manage.py 所在的同一位置创建一个名为 'staticfiles' 的文件夹。 - Helmut Darmüntzel

17

我成功地做到了这一点,通过彻底摆脱if语句并只在我的settings.py中使用以下代码。


import dj_database_url
DATABASES = {
    'default': dj_database_url.config(default='postgres://localhost')
}

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

ALLOWED_HOSTS = ['*']

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'),
)

3
我按照以下三个步骤解决了这个问题:
  1. 在settings.py中导入os模块:import os
  2. 在settings.py中将STATIC_ROOT变量设置为"staticfiles":STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles')
  3. 执行"collectstatic"命令:python manage.py collectstatic

目前你的回答不够清晰,请[编辑]以添加更多细节,帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

0

this网站上,它说要将此URL模式添加到您的项目中:

urlpatterns += patterns(”, (r’^static/(?P.*)$’, ‘django.views.static.serve’, {‘document_root’: settings.STATIC_ROOT}),)

我以前没有使用过Heroku,但是如果我理解正确的话,它需要一个路径来发送所有收集到的静态文件。通常这个路径会在服务器的设置中指定。但是上面的网站提到Heroku使用了一个不支持静态文件部署的应用程序,所以你需要一个URL模式来让它从相应的位置获取静态文件。

另外,在开始之前先阅读整个教程。他们可能在教程的最后或者笔记部分提到了你遇到的问题。如果有评论的话也要读一下。


我尝试将其添加到我的URL模式中,但是它非常不稳定。我将尝试按照教程进行操作。 - ratrace123
当您添加该URL模式时,出错的确切原因是什么? - Eyad Arafat
“patterns”和“settings.STATIC_ROOT”显示为未解决的引用。我不认为我的应用程序设置了这个。我查看了很多类似的问题,似乎我只需要以某种方式设置根目录,但我显然做错了... - ratrace123
仅最后一次尝试。将以下内容添加到urls.py: url(r’^static/(?P.*)$’, ‘django.views.static.serve’, {‘document_root’: settings.STATIC_ROOT})from django.conf import settings - Eyad Arafat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接