Django静态文件在heroku上 [英] Django static files on heroku

查看:113
本文介绍了Django静态文件在heroku上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



然后,我使用git push heroku master创建了一个第二个应用程序,使用当我打开时,heroku创建第二个app -r分段'



并推送:git push staging master



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



这是非常混乱 - 请帮助! p>

我的设置文件位于

  import os 
导入平台
import dj_database_url

DEBUG = True
TEMPLATE_DEBUG = DEBUG

#这应该适用于任何部署
BASE_DIR = os.path.abspath (os.path.join(os.path.dirname(__file__),'..'))

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


MANAGERS = ADMINS
#LOCAL SETTINGS
如果['Windows','Darwin']中的platform.system():
#EV = 'LOCAL'
DATABASES = {
'default':{
'ENGINE':'django.db.backends.sqlite3',#添加'postgresql_psycopg2','mysql','sqlite3'或'oracle'。
'NAME':BASE_DIR +'//db//db.sqlite3',
'USER':'',#不与sqlite3一起使用。
'PASSWORD':'',#不与sqlite3一起使用。
'HOST':'',#设置为localhost的空字符串。不适用于sqlite3。
'PORT':'',#设置为空字符串为默认值。不适用于sqlite3。
}
}
#对本网站有效的主机/域名;如果DEBUG为False,则需要
#请参阅https://docs.djangoproject.com/en/1.4/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []

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

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

#请求request.is_secure()
SECURE_PROXY_SSL_HEADER =('HTTP_X_FORWARDED_PROTO','https')的'X-Forwarded-Proto'标头

#主机/对本网站有效的域名;如果DEBUG为False,则需要
#请参阅https://docs.djangoproject.com/en/1.4/ref/settings/#allowed-hosts
#允许所有主机头
ALLOWED_HOSTS = [' *']

#Todo:ammar - 更新到Memcached
CACHES = {
'default':{
'BACKEND':'django.core.cache。
'b'LOCATION':'unique-snowake',
'TIMEOUT':86400,
'OPTIONS':{'MAX_ENTRIES':10000},
}
}

TIME_ZONE ='欧洲/伦敦'

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',
#取消注释下一个线为简单的劫持保护:
#'django.middleware.clickjacking.XFrameOptionsMiddleware',


ROOT_URLCONF ='sm.urls'

# Python虚线路径到Django的runserver使用的WSGI应用程序。
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',
#取消注释下一行以启用管理员:
'django.contrib .admin',
#取消注释下一行以启用管理员文档:
'django.contrib.admindocs',
'smcore',
'south',
'django.contrib.humanize',




LOGGING = {
'version':1,
'disable_existing_loggers' False,
'filters':{
'require_debug_false':{
'()':'django.utils.log.RequireDebugFalse'
}
},
'处理程序':{
'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 /'

#电子邮件服务器
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',

然后我分支了我的代码(所以我掌握和分期),并将新的英雄遥控器同步到我的分期分支。然后我做了一个git push staging staging:master和它做了一个完整的上传;这再次让我回到同一个地方...帮助!!!

解决方案

最终用下面的我的urls文件 - 从这个问题: Heroku - 处理Django应用程序中的静态文件

 导入设置
urlpatterns + = patterns('',
(r'^ static /(?P< path>。*)$','django.views.static.serve',{'document_root' :settings.STATIC_ROOT}),


I deployed a django app to heroku, using "git push heroku master" which worked absolutely fine.

I then created a second app on the same git using "heroku create second-app -r staging'

and pushed using: git push staging master

when I open second-app, none of the static files are picked up or loaded (ie no css, js, or images work)

This is extremely confusing - please help!

my settings file is below

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'

Update

I took a copy of the code and redeployed, which worked with the following updates to the settings:

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

I then branched my code (so I have master and staging) and synced new heroku remote into my staging branch. I then did a git push staging staging:master and it did a full upload; which has once again got me back to the same place... help!!!

解决方案

Eventually solved this using the below in my urls file - from this question: 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}),
    )

这篇关于Django静态文件在heroku上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆