heroku上的Django静态文件

时间:2014-01-15 15:21:44

标签: django heroku django-staticfiles staticfilehandler

我使用“git push heroku master”将一个django应用程序部署到了heroku,该程序非常好。

然后我使用“heroku create second-app -r staging”在同一个git上创建了第二个应用程序

并推送使用:git push staging master

当我打开第二个应用程序时,没有任何静态文件被拾取或加载(即没有css,js或图像工作)

这非常令人困惑 - 请帮助!

我的设置文件位于

之下
import os
import platform
import dj_database_url

DEBUG = True
TEMPLATE_DEBUG = DEBUG

# This should work for any deployment
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..'))

ADMINS = (
    ('me', 'me@gmailcom'),
)

MANAGERS = ADMINS
# LOCAL SETTINGS
if platform.system() in ['Windows', 'Darwin']:
    #EV = 'LOCAL'
    DATABASES = {
             'default': {
                 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
                 'NAME': BASE_DIR + '//db//db.sqlite3',
                 'USER': '',                      # Not used with sqlite3.
                 'PASSWORD': '',                  # Not used with sqlite3.
                 'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
                 'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
             }
    }
    # Hosts/domain names that are valid for this site; required if DEBUG is False
    # See https://docs.djangoproject.com/en/1.4/ref/settings/#allowed-hosts
    ALLOWED_HOSTS = []

    CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'unique-snowflake',
        'TIMEOUT': 86400,
        'OPTIONS': {
            'MAX_ENTRIES': 10000
            },
        }
    }

# HEROKU SETTINGS
else:
    #EV = 'HEROKU'
    # DEBUG = False
    DATABASES = {}
    DATABASES['default'] =  dj_database_url.config()

    # Honor the 'X-Forwarded-Proto' header for request.is_secure()
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

    # Hosts/domain names that are valid for this site; required if DEBUG is False
    # See https://docs.djangoproject.com/en/1.4/ref/settings/#allowed-hosts
    # Allow all host headers
    ALLOWED_HOSTS = ['*']

    # Todo: ammar - update to Memcached
    CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'unique-snowflake',
        'TIMEOUT': 86400,
        'OPTIONS': {'MAX_ENTRIES': 10000},
        }
    }

TIME_ZONE = 'Europe/London'

LANGUAGE_CODE = 'en-gb'

SITE_ID = 1

USE_I18N = True

USE_L10N = True

USE_TZ = False

MEDIA_ROOT = ''

MEDIA_URL = '/media/'

STATIC_ROOT = ''

STATIC_URL = '/static/'


STATICFILES_DIRS = ()

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)


SECRET_KEY = '***'

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',

)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'sm.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'sm.wsgi.application'

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'mytemplates')
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    'django.contrib.admindocs',
    'smcore',
    'south',
    'django.contrib.humanize',
)



LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/getStarted/'
LOGOUT_URL = '/do_logout/'

# e-mail server
EMAIL_HOST_USER = '***@gmail.com'
EMAIL_HOST= 'smtp.gmail.com'
# EMAIL_PORT = 465
EMAIL_USE_TLS = True
EMAIL_HOST_PASSWORD = '***'
DEFAULT_FROM_EMAIL = '***@gmail.com'
SERVER_EMAIL = '***@gmail.com'

更新

我拿了代码的副本并重新部署,它使用了以下设置更新:

STATIC_ROOT = 'staticfiles'

STATIC_URL = '/static/'

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


STATICFILES_FINDERS = (

    #'django.contrib.staticfiles.finders.FileSystemFinder',
    #'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    #'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

然后我分支了我的代码(所以我有主和分段)并将新的heroku远程同步到我的分段分支。然后我做了一个git push staging staging:master并且它完成了一个完整的上传;这又让我回到了同一个地方......帮助!!!

5 个答案:

答案 0 :(得分:17)

最终在我的网址文件中使用以下内容解决了这个问题 - 来自这个问题:Heroku - Handling static files in Django app

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

答案 1 :(得分:8)

我一直在处理同样的问题。我试图不使用David推荐的解决方案,因为它似乎只用于开发(而不是生产)(参见:Heroku static files not loading, Django

以下是我在代码中更改的两件事。

(我正在使用Django 1.7)

1)settings.py

我将这些行添加到设置文件

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
TEMPLATE_DIRS = (
    os.path.join(BASE_DIR,  'templates'),
    # Add to this list all the locations containing your static files 
)

STATIC_ROOT:这告诉Django(a)在运行“python manage.py collectstatic”时放置静态文件,以及(b)在运行应用程序时找到静态文件

TEMPLATE_DIRS:这告诉Django在运行“python manage.py collectstatic”时搜索静态文件时在哪里查找静态文件

2)wsgi.py

最初我的档案是:

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xxxx.settings")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

我改为:

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xxxx.settings")

from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
application = get_wsgi_application()
application = DjangoWhiteNoise(application)

请阅读此处了解有关whitenoise的更多信息:https://devcenter.heroku.com/articles/django-assets#whitenoise

另外,请记住安装whitenoise:     pip install whitenoise == 2.0.6

在部署项目之前,运行:     python manage.py collectstatic

这将创建一个由STATIC_ROOT指示的文件夹(在settings.py中声明),其中包含所有静态文件。

答案 2 :(得分:3)

这似乎是因为你在没有设置STATIC_ROOT设置的情况下使用了staticfiles应用程序。

相比之下,我的settings.py类似于:

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

您也应该设置STATICFILES_DIRS(请注意,此var的conf可能与您的不一样)

然后,推送您的代码并重试。 如果它仍然不起作用,您可以使用它来调试: https://devcenter.heroku.com/articles/django-assets#debugging

答案 3 :(得分:1)

自Django 1.3以来,您已经能够做到以下

# only showing relevant imports
from django.conf import settings
from django.conf.urls.static import static


urlpatterns = patterns(
    '',

    # your urls go here
)

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL,
                          document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

答案 4 :(得分:0)

对于Django 2.1.7,为了进行工作,我进行了以下更改:

  1. 除了whitenoise

  2. 之外,还将gunicorn添加到了requirements.txt
  3. 项目settings.py应该具有以下内容:

    A)静态设置:

    STATIC_URL = '/static/'
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
    
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, "static"), 
    ]
    

    B)将whitenoise添加到中间件:

    MIDDLEWARE = [
       .....
       'whitenoise.middleware.WhiteNoiseMiddleware',
    ]
    

最后提交并推送您的更改,然后和平部署您的应用。