I am trying to deploy my webapp to heroku. I am using Django and the following is most of my settings.py file:
"""
Django settings for blog project on Heroku. For more info, see:
https://github.com/heroku/heroku-django-template
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
import dj_database_url
import raven
# 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__))
try:
from .local_settings import *
except ImportError:
pass
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
# Disable Django's own staticfiles handling in favour of WhiteNoise, for
# greater consistency between gunicorn and `./manage.py runserver`. See:
# http://whitenoise.evans.io/en/stable/django.html#using-whitenoise-in-development
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
'blogapp',
'homeapp',
'nimfksapp',
'omniclipapp',
#Heroku Sentry
'raven.contrib.django.raven_compat',
]
MIDDLEWARE_CLASSES = [
'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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'blog.urls'
WSGI_APPLICATION = 'blog.wsgi.application'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'live-static', 'static-root')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "live-static", "media-root")
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
When running collectstatic locally the static files get collected fine and are served up on the web page. When I deploy the app to heroku (which automatically runs the collectstatic command for me) it throws up an "Internal Server Error (500)". I followed a recommendation on a similar SO page and added a sentry to the app through heroku and got a clearer error message:
ValueError/nimfks/ errorMissing staticfiles manifest entry for...
I tried changing (and removing) the STATICFILES_STORAGE without success. Removing it got me past the error but trying to display the actual static file (in this case an image) didnt work i.e. it wasnt loading.
I also tried changing the static settings to use PROJECT_ROOT instead of BASE_DIR and a lot of different configurations, all of which didnt work.
Am I missing something here? I cant seem to find an answer in the similar questions asked on SO.
EDIT
Answer:
Embarrasing as it is I want to keep this up since it might help someone else struggling with this. Issue in my case was that I was using .PNG in my html file instead of .png which was the real file extension. Didn't realize this was case sensitive. The real solution to this problem was essentially just having a sentry running that will catch these types of errors (see sentry docs). This is my final version of my static settings in the settings.py file:
import os
import dj_database_url
import raven
# 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__))
MIDDLEWARE_CLASSES = [
'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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
WSGI_APPLICATION = 'blog.wsgi.application'
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'
Try to comment the line
'django.contrib.staticfiles',
inside INSTALLED_APPS
Related
I have developed my web application in Django Framework. I have also made the 404 and 500 Error pages and understand very much that, they can only work when DEBUG=False.
The problem now is that after setting DEBUG=False, my application which I have hosted on Heroku no longer shows. I am also using the whitenoise package for configuring my static files.
This are my settings.py as related to this issue
DEBUG = True
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',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_URL = '/static/'
STATIC_ROOT = 'staticfile'
STATICFILES_DIRS = [BASE_DIR / "static"]
MEDIA_URL = '/media/'
MEDIA_ROOT = "media"
NOTE: I have collected staticfiles using the command heroku run python manage.py collectstaic
I was able to solve the issue. When I removed the whitenoise STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage', I noticed that i no longer got the error which read contact the administartor, and also my page was able to load and the 404 and 500 pages were loading correctly when i set the DEBUG=False
But I noticed that, the images where no longer showing. But I have a feeling that if I use aaws or cloudinary to host the images as well as server them, it should work perfectly.
I'm trying to serve static files in my product review website, and I'm using Whitenoise, but It didn't work (can not find the files in /static) (when I test on local with DEFAULT = False, it still works)
I've tried to config wsgi file instead of using whitenoise middleware
This is my some code in my settings file to serve static.
DEBUG = False
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'djangobower.finders.BowerFinder',
)
Can you show me how to fix it? Pardon for my English
I tried to config the settings again:
DEBUG = False
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# I don't have STATICFILES_DIRS, is it wrong?
STATICFILES_STORAGE = "whitenoise.storage.CompressedStaticFilesStorage"
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'djangobower.finders.BowerFinder',
)
But it still can not serve static files
I believe what you're missing is the STATICFILES_STORAGE. This is my settings.py related configuration.
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
ALLOWED_HOSTS = ["*"]
I followed the below configuration settings to resolve the issue.
DEBUG = False
ALLOWED_HOSTS = ['testnewapp.herokuapp.com']
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
'widget_tweaks',
'phonenumber_field',
'django_extensions',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
# Whitenoise Storage Class - Apply compression but don’t want the caching behaviour
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
# Comment the below line
# django_heroku.settings(locals())
Things to Remember
Make sure you’re using the static template tag to refer to your static files, rather that writing the URL directly. For example:
{% load static %}
<img src="{% static "images/error.jpg" %}" alt="OOps!" />
<!-- DON'T WRITE THIS -->
<img src="/static/images/error.jpg" alt="OOps!" />
If you get an error message with collectstatic, simply disable it by instructing Heroku to ignore running the manage.py collecstatic command during the deployment process.
But if you need to use WhiteNoise with any WSGI application
You need to wrap your existing WSGI application in a WhiteNoise instance and tell it where to find your static files. For example:
from my_project import MyWSGIApp
application = MyWSGIApp()
application = WhiteNoise(application, root='/path/to/static/files')
application.add_files('/path/to/more/static/files', prefix='more-files/')
Note
These instructions apply to any WSGI application. However, for Django applications you would be better off using the WhiteNoiseMiddleware class which makes integration easier.
#
http://whitenoise.evans.io/en/stable/base.html
The static files always give me a 404 error and I can't see why,I copied a style I've used before but not with this version of django.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATIC_DIR = [
os.path.join(BASE_DIR,"static")
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static'
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',
]
I was using cdn and style tag for the whole time working on the project but now i want to wrap it up and use some css/js files already ready for me.
I tried collecting the static files by python manage.py collectstatic and it collected all the static files in the static folder but still doesn't load them and returns a 404 error
my dir:
/Eyelizer
/App1
/App2
/Eyelizer
/static
/css
/main1.css
/Eyelizer
/css
/wanted.css
/js
/wanted.js
/images
/templates
/media
Every kind of help is appreciated and thank you.
I don't think there is anything like STATIC_DIR but it is STATICFILES_DIRS.
And also you have made a typo mistake in STATIC_ROOT while closing the bracket.
Just put the below in settings.py by removing all static related things.
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
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")
Firstly apologies for the length of this.
I have a django project running on Centos6 and Apache using a C-Panel plugin to install Django and I am trying to serve the static files in production.
My project uses Django 1.9 and I am trying to use Whitenoise to serve my static files.
My settings.py contains the following:
STATICFILES_STORAGE ='whitenoise.django.GzipManifestStaticFilesStorage'
STATIC_URL = '/static/'
STATIC_ROOT = STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'common-static'),
And this is my MIDDLEWARE_CLASSES
MIDDLEWARE_CLASSES = [
'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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
)
This is the wsgi.py for my django app
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
application = get_wsgi_application()
And this is the one generated by the plugin:
import os
import sys
import site
vepath = '/home/mysite/virtualenv3.5/lib/python3.5/site-packages'
prev_sys_path = list(sys.path)
site.addsitedir(vepath)
sys.path.append('/home/mysite/djangosites/mysite')
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE","mysite.settings"
application = get_wsgi_application()
I have DEBUG = False in my settings.py.
When I run ./manage.py collectstatic the files are collected and if I run the server with 0.0.0.0:8000 the static files are found.
I tried add the following to both wsgi.py files but to no avail:
from whitenoise.django importDjangoWhiteNoise
application = DjangoWhiteNoise(application)
Any advice on how to solve this would be appreciated.
It's a late response but it might help other people searching for an answer.
You do NOT have to include 'django.middleware.security.SecurityMiddleware' when you're using 'whitenoise.middleware.WhiteNoiseMiddleware'.
Also, you don't need to make any changes in wsgi.py. Adding the middleware will take care of everything for you.