I'm new to Django and I'm trying to understand how django deals with static files. I'm working on building a blog website following a tutorial. here is my project layout:
-myblog
-manage.py
-myblog
-settings.py
-urls.py
-blog
-views.py
-urls.py
-views.py
-static
-blog
-css
-style.css
-templates
-blog
-blog.html
-static
-css
-style.css
-templates
-index.html
but the index.html file can't find it's css file, in index.html file, I have
{% load staticfiles %}
<link href="{% static 'css/style.css' %}" rel="stylesheet">
but it can find the css file in app directory
{% load staticfiles %}
<link href="{% static 'blog/css/style.css' %}" rel="stylesheet">
my settings.py file:
"""
Django settings for myblog 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: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'blog/templates'),
)
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
)
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 = 'myblog.urls'
WSGI_APPLICATION = 'myblog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'myblog',
'USER': 'root',
'PASSWORD': 'q',
'HOST': 'localhost',
'PORT': '3306',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'US/Eastern'
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_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
# os.path.join(BASE_DIR, 'static/'),
os.path.join(BASE_DIR, 'blog/static/'),
)
can anyone tell me what's going on here? Thanks in advance!
You can have as many static files folders as you want, just a)namespace those folders accordingly (static files for the whole project and for an every app separately) and b) provide the path to your static folders within settings file.
In most up-to-date django (1.8) project I have the following settings
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'app_name_here/static/'),
os.path.join(BASE_DIR, 'static/'),
os.path.join(BASE_DIR, 'static/bootstrap-3.3.4'),
)
no STATIC_ROOT defined.
Django can't detect the directories out from your project folder. If you keep the static and templates folder in myblog it will work smoothly.
-myblog
-myblog
-settings.py
-urls.py
-blog
-views.py
-urls.py
-views.py
-static
-blog
-css
-style.css
-templates
-blog
-blog.html
-static
-css
-style.css
-templates
-index.html
Related
I am trying to deploy my fully functional (when local and Debug=True) site to Heroku. When I use the default Django staticfile_storage settings, my site appears live but without any static files (css, images, etc). The admin panel works but it doesn't have any styles either.
But, when I try to use Whitenoise, which is what I originally intended, I get a server 500 error. The admin panel will not work then. I can't figure out for the life of me what I am doing wrong.
I have tried to model my settings.py file after Heroku's template:
https://github.com/heroku/heroku-django-template, and Whitenoise's documentation http://whitenoise.evans.io/en/latest/django.html.
When I look at my most recent Heroku logs, I see
at=info method=GET path="/static/css/styles.css" host=www.mysite.net request_id=826280da-21ba-48a1-8a05-679c92871d38 dyno=web.1 connect=0ms service=3ms status=404 bytes=361
When I push to Heroku, deployment is successful, but when I run
heroku run python3 manage.py collectstatic
it says that I have to write over preexisting files (yes/no), and when I say yes, I get an error stating that the app/static directory is not to be found.
I am absolutely puzzled - what could I be doing wrong? If my static files directory is not correct, how do I find it?
project structure
mysite/
blog/
static/
css/
styles.css
images/
favicon.png
templates/
blog/
blog_list.html
blog_detail.html
index.html
bio.html
resume.html
models.py
views.py
urls.py
media/
portfoliopieces/
1.png
2.png
3.png
4.png
mysite/
settings.py
urls.py
wsgi.py
portfolio/
templates/
portfolio_list.html
portfolio_detail.html
models.py
views.py
urls.py
mysite/urls.py
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
import os
from secrets import *
import dj_database_url
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
# SECURITY WARNING: keep the secret key used in production secret!
# see secrets.py
# SECURITY WARNING: don't run with debug turned on in production!
# DEBUG = bool(os.environ.get('DJANGO_DEBUG', True))
# For production, make false
DEBUG = False
ALLOWED_HOSTS = ['www.mysite.com' ]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
'portfolio.apps.PortfolioConfig',
'blog.apps.BlogConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
WSGI_APPLICATION = 'mysite.wsgi.application'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
# STATIC_URL = '/static/'
STATIC_DIR = os.path.join(BASE_DIR, 'static')
# STATICFILES_DIRS = [
#os.path.join(BASE_DIR, "static"),
#]
# STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
os.path.join(PROJECT_ROOT, 'static'),
]
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
# STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
# Update database configuration with $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
After two full days of trying to get whitenoise to work, and failing, I figured out how to make the default Django staticfiles work over Heroku. This was really tricky, this might help others: the settings.py file should(assuming my project structure) look like this:
import os
from secrets import *
import dj_database_url
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = False
ALLOWED_HOSTS = ['www.mysite.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'portfolio.apps.PortfolioConfig',
'blog.apps.BlogConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Heroku: Update database configuration from $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Static files (CSS, JavaScript, Images)
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")
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'),
)
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
So I'm pulling apart a website with the front-end already built and have taken on the task of building out the backend, but I am new to django. I have managed to separate everything out accordingly (css, js, img's in a static folder, html files in a templates folder, etc) and so far have been able to set the index.html as the homepage to django. Within this index.html file, other html files (located in the templates folder along with the index.html file) are being loaded within tags of the index.html file. Currently all of the images, css, and js is coming through in the file, but the html files are not. I am referencing these html files as "name of file.html" However, I cannot seem to get these to load unless I move the templates folder into the static folder (alongside the css, images, js, etc.) and change the reference to "static/templates/name of file.html"
My project setup is as follows. Also I'm running django 1.7.
atmos_v4/
atmos_v4/
init__.py
settings.py
urls.py
wsgi.py
db.sqlite3
manage.py
static/
css/
...
img/
...
js/
...
media/
...
templates/
index.html
...
My urls.py and settings.py are below. I have a feeling my TEMPLATE_DIRS and STATIC_ROOT may be set up incorrectly. If not, would someone be so kind as to tell me what I'm missing? Thank you!
settings.py:
"""
Django settings for atmos_v4 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 = 'y=3ey3sv8lm1j358(2bgthtx0bzy_cjaxug#2npx029nfs#5i%'
# 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',
)
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 = 'atmos_v4.urls'
WSGI_APPLICATION = 'atmos_v4.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# 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/'
from os.path import join
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
STATIC_PATH = os.path.join(BASE_DIR,'static')
STATICFILES_DIRS = (
STATIC_PATH,
)
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name="index.html")),
url(r'^admin/', include(admin.site.urls)),
)
index.html reference examples
<div id="wheelartist" style="position:absolute; top:131px; left:536px; z- index:999999;">
<div id="circleartist" class="circleartist">
<a id="homebuttonLink" href="artist_profile.html"><img id="homebutton" title="Home" src="/static/img/icons/user.png" alt=""></a>
<a id="msgsbuttonLink" href="messages.html"><img id="msgsButton" title="Messages" src="/static/img/icons/mail.png" alt=""></a>
<a id="directorybuttonLink" href="directory.html"><img id="directoryButton" title="Directory" src="/static/img/icons/book.png" alt=""> </a>
<a id="cartbuttonLink" href="shopping_cart.html"><img id="cartButton" class="shopingCart" title="Shopping Cart" src="/static/img/icons/shopping.png" alt=""></a>
<a id="contestsbuttonLink" href="contests_list.html"><img id="contestsButton" class="planet" title="Planet" src="/static/img/icons/planet.png" alt=""></a>
<a id="pointsbuttonLink" href="points.html"><img id="pointsButton" class="awards" title="Awards" src="/static/img/icons/awards.png" alt=""></a>
<a id="prefbuttonLink" href="preferences.html"><img id="prefButton" class="tools" title="Tools" src="/static/img/icons/tools.png" alt=""></a>
<a id="searchbuttonLink" href="search.html"><img id="searchButton" class="headphones" title="Search" src="/static/img/icons/music.png" alt=""></a>
<a id="mapbuttonLink" href="artist_careermap.html"><img id="mapButton" title="Career Map" src="/static/img/icons/map.png" alt=""></a>
<a id="profitsbuttonLink" href="artist_profits.html"><img id="profitsButton" title="Profits" src="/static/img/icons/profits.png" alt=""></a>
<a id="statsbuttonLink" href="artist_stats.html"><img id="statsButton" title="Stats" src="/static/img/icons/stats.png" alt=""></a> </div>
templates/
index.html
try to change to this structure
templates/
atmos_v4/
index.html
and inside the settings.py remove this
"from os.path import join"
EDIT: after you update your file now i see that you have bad index.html file, you need to use the built-in function for templates and url
https://docs.djangoproject.com/en/1.7/ref/templates/builtins/#url
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.