Django Heroku 静态文件设置

3 投票
1 回答
2311 浏览
提问于 2025-04-18 06:22

我有一个Django应用程序,在本地运行静态文件没问题。但是当我把它推送到Heroku时,它在找静态文件的位置时出现了问题(它在找home/www_dev/www_dev/settings/static)。

文件结构:

home
> www_dev
>>> organizations (my app)
>>> static
>>> www_dev
>>>>> settings

base.py设置:(使用了《Two Scoops of Django》模板)

STATIC_ROOT = normpath(join(SITE_ROOT, 'assets'))
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    normpath(join(SITE_ROOT, 'static')),
)
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

production.py设置:(参考了Heroku的文档)

# Static asset configuration
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'

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

wsgi.py:

import os
from os.path import abspath, dirname
from sys import path

SITE_ROOT = dirname(dirname(abspath(__file__)))
path.append(SITE_ROOT)

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "www_dev.settings.production")

from django.core.wsgi import get_wsgi_application
from dj_static import Cling

application = Cling(get_wsgi_application())

Procfile:

web: gunicorn --pythonpath www_dev www_dev.wsgi -b 0.0.0.0:$PORT

我尝试按照其他Stack Overflow帖子中的建议,添加到urls.py,但没有成功:

if not settings.DEBUG:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)$', 'django.contrib.staticfiles.views.serve', {'document_root': settings.STATIC_ROOT}),
    )

Heroku错误:

-----> Preparing static assets
       Collectstatic configuration error. To debug, run:
       $ heroku run python ./www_dev/manage.py collectstatic --noinput

运行collectstatic的结果:

OSError: [Errno 2] No such file or directory: '/app/www_dev/www_dev/settings/static'

如果我无法解决这个问题,我愿意直接使用S3,但我在使用django-storages和boto将本地静态文件(CSS/JS)推送到S3时遇到了麻烦。只要能把所有媒体文件放在S3上,我就可以接受。非常感谢任何帮助!

1 个回答

2

在你的 settings/production.py 文件中修改 STATIC_ROOT 的设置。

如果你不需要使用不同的静态文件根目录,可以直接删除这个变量,因为它已经在 setting/base.py 中定义过了。

这个 Heroku 文档 假设你只使用一个 settings.py 文件,这个文件位于 project_dir/settings.py。

撰写回答