小编典典

Heroku-在Django应用中处理静态文件

django

我在heroku中有一个项目(myapp),但无法使静态文件正常工作。

我的Procfile样子是这样的:

web: python myapp/manage.py collectstatic --noinput; bin/gunicorn_django --workers=4 --bind=0.0.0.0:$PORT myapp/settings.py

settings.py:

...

STATIC_ROOT = os.path.join(PROJECT_PATH, 'staticfiles')
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'

STATICFILES_DIRS = (
    # I have the static folder inside my app and not inside the project
    os.path.join(PROJECT_PATH, 'cesar/static'),
)

...

重新启动时heroku restart,将heroku logs显示以下内容:

...
Copying ...

114 static files copied to '/app/myapp/staticfiles'.
...

但是当我这样做时,我heroku run ls -l myapp/看不到该staticfiles文件夹:

-rw------- 1 u5605 5605    0 Jan 28 16:53 __init__.py
drwx------ 4 u5605 5605 4096 Jan 28 16:53 cesar
-rw------- 1 u5605 5605  503 Jan 28 16:53 manage.py
-rw------- 1 u5605 5605 6292 Jan 28 16:53 settings.py
drwx------ 2 u5605 5605 4096 Jan 28 16:53 templates
-rw------- 1 u5605 5605  257 Jan 28 16:53 urls.py
-rw------- 1 u5605 5605  286 Jan 28 16:53 views.py

阅读 546

收藏
2020-03-29

共1个答案

小编典典

我找到了解决方案。这是我最初的myapp/urls.py

from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.conf import settings


admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', include('myapp.cesar.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

我将这些行添加到原始myapp/urls.py文件的末尾:

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

现在一切正常。我希望这也可以帮助其他人

2020-03-29