Setting up Django app on Heroku + Amazon S3 - django

I've successfully deployed a live Django app on Heroku for the first time. However, I didn't realize that Heroku doesn't store media files - I want the admin to be able to upload images to the app - so I am trying to setup Amazon S3. This is my first time doing this setup.
1)My settings.py file includes this...
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': "os.path.join(BASE_DIR, 'db.sqlite3')", # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
MEDIA_ROOT = '/media/'
MEDIA_URL = S3_URL + MEDIA_ROOT
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# List of callables that know how to import templates from various sources.
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 = 'listing.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'listing.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
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',
'noticeboard',
'django_extensions',
'south',
'PIL',
'storages',
'boto',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
DATABASES['default'] = dj_database_url.config()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']
ASW_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']
S3_BUCKET_NAME = os.environ['S3_BUCKET_NAME']
STATICFILES_STORAGE = 'storages.backends.s3boto.s3BotoStorage'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.s3BotoStorage'
S3_URL = 'http://s3.amazonaws.com/%s' % S3_BUCKET_NAME
2) I've updated my requirements.txt file to include the boto and storages modules
3) I've setup my Heroku config file to include my bucket name, AWS Key and secret key.
This is the error I'm getting when I upload an image from the admin, it seems as if it's still trying to access the files on Heroku and not S3:
Exception Type: OSError
Exception Value:
[Errno 30] Read-only file system: '/Users'
Exception Location: /app/.heroku/python/lib/python2.7/os.py in makedirs, line 157
Python Executable: /app/.heroku/python/bin/python
Python Version: 2.7.4
I've read a few blog posts about this that say the same thing but I'm stuck as to why this isn't working!

Related

Django hosting static files on the server

I am trying to deploy my Django project on the server. But, when I use it, the static file on Django can not be read correctly
I deploy my project on Debian server. The static file of course in same server, I have succeeded in deploying my project. But static files like css still can not appear in my project
This is my settings files:
"""
Django settings for akun project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
PROJECT_DIR = os.path.join(PROJECT_ROOT)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '8g*v#sf1i0y#+#5jyy$kk)wlixu*9yo(t$&1n%59ip*391sy#u'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'simofa',
'accounts',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'akun.urls'
WSGI_APPLICATION = 'akun.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'pgina',
'USER': 'root',
'PASSWORD': '123',
'HOST': 'localhost', # Or an IP Address that your DB is hosted on
'PORT': '3306',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Jakarta'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
# template location
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(PROJECT_ROOT), "static", "templates"),
'/home/boss/kantor/akun/templates/',
)
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(PROJECT_DIR),"static","static-only")
MEDIA_ROOT = os.path.join(os.path.dirname(PROJECT_DIR),"static","media")
STATICFILES_DIRS = os.path.join(os.path.dirname(PROJECT_DIR),"static","static"),
i'm trying to change STATIC_URL='/static/' to the url STATIC_URL='http://www.url.com/my_project/static'
but the result still doesn't appears
When i try in my localhost, it works properly.
how is the solution ?
In production you need first to define STATIC_ROOT and then run collectstatic in order to have your static files collected there.
After running collectstatic you should be able to cd to the dir associated to STATIC_ROOT and see the files.
EDIT: the code below should be added in he Apache conf file, not in the Django settings
Finally if you are using Apache (and you are serving the files from the same server where you are running the Django app) you will need to serve the path of the STATIC_ROOT under the url defined in STATIC_URL, for example assuming STATIC_URL is /static/:
Alias /static/ /path/to/mysite.com/static_root_directory/
and then set permissions:
<Directory /path/to/mysite.com/static_root_directory>
Require all granted
</Directory>
PS you didn't provide many details about your environment (server, static on same server or not) so I had to make assumptions. If you provide more details I'm happy to help.
Static files dirs should be a tuple
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)

How to deploy static files with Django

I've been trying to deploy the static .css files and stuff for a website my classmates and I have been doing. Right now we have kind of crap styling and stuff so we decided to use some code from Bootstrap to make it looks nice.
After editing my settings.py and doing python manage.py collectstatic, the static files were put into the static/ folder. Upon using the runserver command, none of the styling changes have been made. I've been looking on Google for a while but I have not discovered the solution.
I want to get it working on my local machine before I push it to PythonAnywhere.
Any help will be appreciated.
Here is my settings.py file
"""
Django settings for Dreadnaught project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = GOTCHA!
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'TTT'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'Dreadnaught.urls'
WSGI_APPLICATION = 'Dreadnaught.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'Dreadnaught',
'USER': 'root',
'PASSWORD': 'root',
'HOST': '',
'PORT': '',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
STATIC_PATH = os.path.join(BASE_DIR, 'static')
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = ()
TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
TEMPLATE_DIRS = (TEMPLATE_PATH,)
If you want to serve your css and js files in production mode you must change Debug true to false.
DEBUG=False
For reference STATIC

I have deployed my django project in pythonanywhere, DATABASES is improperly configured error

I have deployed my django project in pythonanywhere without any databases required, I am getting the error- DATABASES is improperly configured . The link to my deployed project is -http://drchitradhawle.pythonanywhere.com/
My setting.py file is-
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'fi+9_egiio(7l6xvbgk%o=!k(ktn3!ywhc4+p_6^57j4yvl0tp'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'webpage',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'website.urls'
WSGI_APPLICATION = 'website.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_ROOT = "/home/DrChitraDhawle/website/webpage/static"
STATIC_URL = '/static/'
STATICFILES_DIR = (
('assets', '/home/DrChitraDhawle/website/webpage'),
)
#
#STATICFILES_DIR = [os.path.join(BASE_DIR, '')]
MEDIA_URL = 'http://localhost:8085/media/'
Django needs a database to store information such as session/cookie info. So even if you don't use the database for your own website stuff, you still need one.
Fortunately, just using the default sqlite settings, and then running ./manage.py syncdb should be enough to get everything working for now.
Although you don't want to use database in your project but still you have to give database defination as #conrad said. So you can use sqlite3, a file based database that does not require setting up a database account and password.
Set up your database setting as -
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/home/<username>/<ProjectName>/db.sqlite',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': ''
}
}
After that run the below command in console -
python ./manage.py syncdb
Now you will be asked for password, username and email-Id for creating superuser for database.
And its all done!

ImproperlyConfigured error when logging into django site while using mongoengine

I am using Django in conjunction with MongoDB using mongoengine. I was following the tutorial on https://docs.djangoproject.com/en/1.7/intro/tutorial02/ and therefore wanted to create a superuser and log in. Creation worked without problem appearantly. However when I tried to log in, I was greeted by the following site:
I suppose this has to do with my initialization of the database using the dummy database in the settings.py. However I was told using mongoengine requires to do it this way and it did not cause problems earlier. Anyway: here is the content of my settings.py
"""
Django settings for myproject project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'xg0wnp^w)i#svh13#^v45**4^3v-at#ktre=^n#cw2!6(q__gq'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.auth',
'mongoengine.django.mongo_auth',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'myproject.urls'
WSGI_APPLICATION = 'myproject.wsgi.application'
import mongoengine
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
#DATABASES = {
# 'default' : {
# 'ENGINE' : 'django_mongodb_engine',
# 'NAME' : 'my_database'
# }
#}
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
#}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.dummy',
}
}
mongoengine.connect(db='local', alias ='default')
#from django.contrib.auth import get_user_model
#user = get_user_model().objects.create_user(**user_data)
AUTHENTICATION_BACKENDS = (
'mongoengine.django.auth.MongoEngineBackend',
)
AUTH_USER_MODEL = 'mongo_auth.MongoUser'
MONGOENGINE_USER_DOCUMENT = 'mongoengine.django.auth.User'
#MONGOENGINE_USER_DOCUMENT = 'mongoengine.django.auth.User'
#SESSION_ENGINE = 'mongoengine.django.sessions'
#SESSION_SERIALIZER = 'mongoengine.django.sessions.BSONSerializer'
#_MONGODB_USER = 'mongouser'
#_MONGODB_PASSWD = 'password'
#_MONGODB_HOST = 'thehost'
#_MONGODB_NAME = 'thedb'
#_MONGODB_DATABASE_HOST = \
# 'mongodb://%s:%s#%s/%s' \
# % (_MONGODB_USER, _MONGODB_PASSWD, _MONGODB_HOST, _MONGODB_NAME)
#mongoengine.connect(_MONGODB_NAME, host=_MONGODB_DATABASE_HOST)
#AUTHENTICATION_BACKENDS = (
# 'mongoengine.django.auth.MongoEngineBackend',
#)
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
Kindly configure the following settings in setting.py file
import mongoengine
DATABASES = {
'default': {
'ENGINE': '',
},
}
SESSION_ENGINE = 'mongoengine.django.sessions' # optional
_MONGODB_USER = 'mongouser'
_MONGODB_PASSWD = 'password'
_MONGODB_HOST = 'thehost'
_MONGODB_NAME = 'thedb'
_MONGODB_DATABASE_HOST = \
'mongodb://%s:%s#%s/%s' \
% (_MONGODB_USER, _MONGODB_PASSWD, _MONGODB_HOST, _MONGODB_NAME)
mongoengine.connect(_MONGODB_NAME, host=_MONGODB_DATABASE_HOST)
AUTHENTICATION_BACKENDS = (
'mongoengine.django.auth.MongoEngineBackend',
)
I hope the above solution will resolve your issue.
what to do if database-engine not needed
default database is used by some of the default authentication APIs
used in Middleware-Apps.
try to make your MIDDLEWARE_APPS tuple as follows:
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
# 'django.contrib.auth.middleware.AuthenticationMiddleware',
# 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
I am just a beginner, so if any more errors come around please do comment.
This solution breaks the default Admin Panel backend provided by Django. I'm trying to find a work around for the same.
Redirecting to a different view in urls.py for admin page may help
though

Django static files on heroku

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}),
)
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.
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
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)
For Django 2.1.7, I did the following changes in order to work:
Added whitenoise to requirements.txt in addition to gunicorn
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.