Django static files on heroku

23k views Asked by At

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!!!

5

There are 5 answers

2
Ammar Akhtar On BEST ANSWER

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}),
    )
4
David Dahan On

It seems that it's because you're using the staticfiles app without having set the STATIC_ROOT setting.

In comparison, my settings.py is something like:

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

You should set the STATICFILES_DIRS too (note that my conf for this var is probably not the same than yours)

Then, push your code and try again. If it still doesn't work, you can use this to debug : https://devcenter.heroku.com/articles/django-assets#debugging

0
Matt Briançon On

Since Django 1.3 you've been able to do the following

# 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)
0
phanhuy152 On

I have been dealing with the same problem too. I tried not to use the solution recommended by David since it seems to be used only in development (and not production) (See: Heroku static files not loading, Django)

And here are the 2 things that I changed in my code.

(I'm using Django 1.7)

1) settings.py

I add these lines to the setting files

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: this tells Django where to (a) put the static files when you run "python manage.py collectstatic" and (b) find the static files when you run the application

TEMPLATE_DIRS: this tells Django where to look for your static files when it search for statics files when you run "python manage.py collectstatic"

2) wsgi.py

Originally my file was:

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

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

And I changed it to:

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)

Read here for more information on whitenoise: https://devcenter.heroku.com/articles/django-assets#whitenoise


Also, remember to install whitenoise: pip install whitenoise==2.0.6

Before deploying the project, run: python manage.py collectstatic

This will create a folder indicated by STATIC_ROOT (declared in your settings.py), containing all your static files.

0
Ali Ezzat Odeh On

For Django 2.1.7, I did the following changes in order to work:

  1. Added whitenoise to requirements.txt in addition to gunicorn

  2. Project settings.py should have the following:

    A) static settings:

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

    B) Add whitenoise to middleware:

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

Finally commit and push your changes then deploy your app peacefully.