2013-07-05 67 views
4

我有Django的一個應用程序,我部署它在Heroku,但我無法服務於服務器上的靜態文件,下面是我的代碼,並設置:如何服務的Django在Heroku靜態文件與gunicorn

設置。 PY

DEBUG = True 
TEMPLATE_DEBUG = DEBUG 
import os 
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__)) 
SITE_PATH = os.path.abspath(os.path.join(PROJECT_PATH, os.path.pardir)) 

STATIC_ROOT = '' 
STATIC_URL = '/static/' 
STATICFILES_DIRS = (
    os.path.join(SITE_PATH, 'staticfiles'),) 
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder', 
    'django.contrib.staticfiles.finders.AppDirectoriesFinder', 
# 'django.contrib.staticfiles.finders.DefaultStorageFinder', 
) 

urls.py

from django.conf import settings 
from django.conf.urls import patterns, include, url 
from polls.views import VoteClassBasedView 
from django.contrib import admin 
admin.autodiscover() 


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

Procfile

web: gunicorn django_polls.wsgi 

我的本地目錄結構

drwxrwxr-x 2 user1 user1 4096 Jul 5 11:48 django_polls/ 
-rwxr-xr-x 1 user1 user1 255 Jun 22 15:50 manage.py* 
drwxrwxr-x 5 user1 user1 4096 Jul 3 14:41 polls/ 
-rw-r--r-- 1 user1 user1 50176 Jul 5 11:41 polls.db 
-rw-rw-r-- 1 user1 user1 32 Jul 4 18:57 Procfile 
-rw-rw-r-- 1 user1 user1 338 Jun 25 18:51 README.md 
-rw-rw-r-- 1 user1 user1 310 Jul 4 17:09 requirements.txt 
drwxrwxr-x 5 user1 user1 4096 Jul 4 17:57 staticfiles/ 
                 /bootstrap 
                 /admin 
                 /polls 
drwxrwxrwx 3 user1 user1 4096 Jun 22 18:59 templates/ 

Heroku的文件結構

drwx------ 2 u19068 19068 4096 2013-07-05 11:31 django_polls/ 
-rwx------ 1 u19068 19068 255 2013-07-05 11:28 manage.py* 
drwx------ 5 u19068 19068 4096 2013-07-05 11:31 polls/ 
-rw------- 1 u19068 19068 32 2013-07-05 11:28 Procfile 
-rw------- 1 u19068 19068 338 2013-07-05 11:28 README.md 
-rw------- 1 u19068 19068 310 2013-07-05 11:28 requirements.txt 
-rw------- 1 u19068 19068 13 2013-07-05 11:28 runtime.txt 
drwx------ 5 u19068 19068 4096 2013-07-05 11:28 staticfiles/ 
                  /bootstrap 
                  /admin 
                  /polls 
drwx------ 3 u19068 19068 4096 2013-07-05 11:28 templates/ 

上面的代碼是能夠服務於這個css文件的本地機器上(其實我與引導結合),但提交之後到heroku git hub並運行類似polls.herokuapp.com/polls/的url,它提供html文件和整個功能,但無法提供css文件。

另外,當我運行命令foreman start它也提供靜態(css,js)文件,但部署在heroku上時相同的代碼無法服務器靜態文件。

任何人都可以請讓我知道在Heroku上部署Django應用程序需要做什麼修改?

請注意,我已完成R & D並應用各種代碼,例如在urls.py中使用from django.contrib.staticfiles.urls import staticfiles_urlpatterns,但無法獲得解決方案。

回答

0

爲靜態文件,我強烈建議您使用白噪聲http://whitenoise.evans.io/en/stable/django.html

STATIC_ROOT = os.path.join(PROJECT_PATH, 'staticfiles') 
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' 
MIDDLEWARE_CLASSES = [ 
    # 'django.middleware.security.SecurityMiddleware', 
    'whitenoise.middleware.WhiteNoiseMiddleware', 
    # ... 
] 

無需運行collectstatic同Heroku會爲你做的。所做的就是將所有文件放入STATIC_ROOT(全部壓縮並且長時間過期並使用哈希文件名)。

相關問題