I am trying to set up multiple setting files (development, production, ..) that include some base settings. Cannot succeed though. When I try to run ./manage.py runserver I am getting the following error:
(cb)clime#den /srv/www/cb $ ./manage.py runserver
ImproperlyConfigured: The SECRET_KEY setting must not be empty.
Here is my settings module:
(cb)clime#den /srv/www/cb/cb/settings $ ll
total 24
-rw-rw-r--. 1 clime clime 8230 Oct 2 02:56 base.py
-rw-rw-r--. 1 clime clime 489 Oct 2 03:09 development.py
-rw-rw-r--. 1 clime clime 24 Oct 2 02:34 __init__.py
-rw-rw-r--. 1 clime clime 471 Oct 2 02:51 production.py
Base settings (contain SECRET_KEY):
(cb)clime#den /srv/www/cb/cb/settings $ cat base.py:
# Django base settings for cb project.
import django.conf.global_settings as defaults
DEBUG = False
TEMPLATE_DEBUG = False
INTERNAL_IPS = ('127.0.0.1',)
ADMINS = (
('clime', 'clime7#gmail.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'cwu', # Or path to database file if using sqlite3.
'USER': 'clime', # 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.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Europe/Prague'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = False
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = False # TODO: make this true and accustom date time input
DATE_INPUT_FORMATS = defaults.DATE_INPUT_FORMATS + ('%d %b %y', '%d %b, %y') # + ('25 Oct 13', '25 Oct, 13')
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/srv/www/cb/media'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = '/srv/www/cb/static'
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '8lu*6g0lg)9z!ba+a$ehk)xt)x%rxgb$i1&022shmi1jcgihb*'
# 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',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.request',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'web.context.inbox',
'web.context.base',
'web.context.main_search',
'web.context.enums',
)
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',
'watson.middleware.SearchContextMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'middleware.UserMemberMiddleware',
'middleware.ProfilerMiddleware',
'middleware.VaryOnAcceptMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'cb.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'cb.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.
'/srv/www/cb/web/templates',
'/srv/www/cb/templates',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
'grappelli', # must be before admin
'django.contrib.admin',
'django.contrib.admindocs',
'endless_pagination',
'debug_toolbar',
'djangoratings',
'watson',
'web',
)
AUTH_USER_MODEL = 'web.User'
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'formatters': {
'standard': {
'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt' : "%d/%b/%Y %H:%M:%S"
},
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
'null': {
'level':'DEBUG',
'class':'django.utils.log.NullHandler',
},
'logfile': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': "/srv/www/cb/logs/application.log",
'maxBytes': 50000,
'backupCount': 2,
'formatter': 'standard',
},
'console':{
'level':'INFO',
'class':'logging.StreamHandler',
'formatter': 'standard'
},
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
'django': {
'handlers':['console'],
'propagate': True,
'level':'WARN',
},
'django.db.backends': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': False,
},
'web': {
'handlers': ['console', 'logfile'],
'level': 'DEBUG',
},
},
}
LOGIN_URL = 'login'
LOGOUT_URL = 'logout'
#ENDLESS_PAGINATION_LOADING = """
# <img src="/static/web/img/preloader.gif" alt="loading" style="margin:auto"/>
#"""
ENDLESS_PAGINATION_LOADING = """
<div class="spinner small" style="margin:auto">
<div class="block_1 spinner_block small"></div>
<div class="block_2 spinner_block small"></div>
<div class="block_3 spinner_block small"></div>
</div>
"""
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
}
import django.template.loader
django.template.loader.add_to_builtins('web.templatetags.cb_tags')
django.template.loader.add_to_builtins('web.templatetags.tag_library')
WATSON_POSTGRESQL_SEARCH_CONFIG = 'public.english_nostop'
One of the setting files:
(cb)clime#den /srv/www/cb/cb/settings $ cat development.py
from base import *
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1', '31.31.78.149']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'cwu',
'USER': 'clime',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
MEDIA_ROOT = '/srv/www/cb/media/'
STATIC_ROOT = '/srv/www/cb/static/'
TEMPLATE_DIRS = (
'/srv/www/cb/web/templates',
'/srv/www/cb/templates',
)
Code in manage.py:
(cb)clime#den /srv/www/cb $ cat manage.py
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cb.settings.development")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
If I add from base import * into /srv/www/cb/cb/settings/__init__.py (which is otherwise empty), it magically starts to work but I don't understand why. Anyone could explain to me what's going on here? It must be some python module magic.
EDIT: Everything also starts to work if I remove this line from base.py
django.template.loader.add_to_builtins('web.templatetags.cb_tags')
If I remove this line from web.templatetags.cb_tags, it also starts to work:
from endless_pagination.templatetags import endless
I guess it is because, in the end, it leads to
from django.conf import settings
PER_PAGE = getattr(settings, 'ENDLESS_PAGINATION_PER_PAGE', 10)
So it creates some weird circular stuff and game over.
I had the same error and it turned out to be a circular dependency between a module or class loaded by the settings and the settings module itself. In my case it was a middleware class which was named in the settings which itself tried to load the settings.
I ran into the same problem after restructuring the settings as per the instructions from Daniel Greenfield's book Two scoops of Django.
I resolved the issue by setting
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings.local")
in manage.py and wsgi.py.
Update:
In the above solution, local is the file name (settings/local.py) inside my settings folder, which holds the settings for my local environment.
Another way to resolve this issue is to keep all your common settings inside settings/base.py and then create 3 separate settings files for your production, staging and dev environments.
Your settings folder will look like:
settings/
__init__.py
base.py
local.py
prod.py
stage.py
and keep the following code in your settings/__init__.py
from .base import *
env_name = os.getenv('ENV_NAME', 'local')
if env_name == 'prod':
from .prod import *
elif env_name == 'stage':
from .stage import *
else:
from .local import *
I had the same error with python manage.py runserver.
For me, it turned out that it was because of a stale compiled binary (.pyc) file. After deleting all such files in my project, server started running again. :)
So if you get this error, out of nowhere, i.e without making any change seemingly-related to django-settings, this could be a good first measure.
Remove .pyc files
Ubuntu terminal command for deleting .pyc :
find . -name "*.pyc" -exec rm -rf {} \;
I have got same error when I did python manage.py runserver. It was because .pyc file. I deleted .pyc file from project directory then it was working.
I hadn't specified the settings file:
python manage.py runserver --settings=my_project.settings.develop
I had the same problem with Celery. My setting.py before:
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
after:
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', <YOUR developing key>)
If the environment variables are not defined then: SECRET_KEY = YOUR developing key
It starts working because on the base.py you have all information needed in a basic settings file. You need the line:
SECRET_KEY = '8lu*6g0lg)9z!ba+a$ehk)xt)x%rxgb$i1&022shmi1jcgihb*'
So it works and when you do from base import *, it imports SECRET_KEY into your development.py.
You should always import basic settings before doing any custom settings.
EDIT:
Also, when django imports development from your package, it initializes all variables inside base since you defined from base import * inside __init__.py
I think that it is the Environment error,you should try setting : DJANGO_SETTINGS_MODULE='correctly_settings'
For anyone using PyCharm: the green "Run selected configuration" button would produce this error, yet running the following works:
py manage.py runserver 127.0.0.1:8000 --settings=app_name.settings.development
To fix this you need to edit the configuration's environment variables. To do this click the "Select run/debug configuration" drop-down menu to the left of the green run button and then click on "edit configuration". Under the "environment" tab change the environment variable DJANGO_SETTINGS_MODULE to app_name.settings.development.
for development just update settings.py, and should work
SECRET_KEY = '*'
In the init.py of the settings directory write the correct import, like:
from Project.settings.base import *
No need to change wsgi.py or manage.py
I solved this problem occurring on OS X with Django both 1.5 and 1.6 by deactivating all active sessions to virtualenv and starting it again.
To throw another potential solution into the mix, I had a settings folder as well as a settings.py in my project dir. (I was switching back from environment-based settings files to one file. I have since reconsidered.)
Python was getting confused about whether I wanted to import project/settings.py or project/settings/__init__.py. I removed the settings dir and everything now works fine.
I just wanted to add that I got this error when my database name was spelled wrong in my settings.py file so the DB couldn't be created.
I solved this problem on 1.8.4 by fixing the TEMPLATES settings which had a typo (removing TEMPLATES['debug'] solved it)
Go over the settings that you have changed recently, make sure all keys are by-the-book.
My Mac OS didn't like that it didn't find the env variable set in the settings file:
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('MY_SERVER_ENV_VAR_NAME')
but after adding the env var to my local Mac OS dev environment, the error disappeared:
export MY_SERVER_ENV_VAR_NAME ='fake dev security key that is longer than 50 characters.'
In my case, I also needed to add the --settings param:
python3 manage.py check --deploy --settings myappname.settings.production
where production.py is a file containing production specific settings inside a settings folder.
The issue for me was calling get_text_noop in the LANGUAGES iterable.
Changing
LANGUAGES = (
('en-gb', get_text_noop('British English')),
('fr', get_text_noop('French')),
)
to
from django.utils.translation import gettext_lazy as _
LANGUAGES = (
('en-gb', _('British English')),
('fr', _('French')),
)
in the base settings file resolved the ImproperlyConfigured: The SECRET_KEY setting must not be empty exception.
The reason why there are so many different answers is because the exception probably doesn't have anything to do with the SECRET_KEY.
It is probably an earlier exception that is being swallowed.
Turn on debugging using DEBUG=True to see the real exception.
In my case, it was because I was trying to setup django-environ and I missed an important step:
Note: In the instructions below .env.example and .env should be saved in the same folder as settings.py
I incorrectly assumed that .env belonged in the root of my project. Moving it to the same folder as settings.py fixed the problem.
This error message in the Python console was the clue that set me on the right path:
Warning: /Users/allen/PycharmProjects/myapp/myapp/.env doesn't exist - if you're not configuring your environment separately, create one.
I solved this problem by removing the spaces around equal signs (=) in my .env file.
In my case the problem was - I had my app_folder and settings.py in it. Then I decided to make Settings folder inside app_folder - and that made a collision with settings.py. Just renamed that Settings folder - and everything worked.
I solved the above problem by commenting the line in my settings.py
SECRET_KEY=os.environ.get('SECRET_KEY')
SECRET_KEY declared in my ~/.bashrc file(for linux Ubuntu users)
For development purpose on my localmachine I did not use evironmnet variable
SECRET_KEY = '(i9b4aes#h1)m3h_8jh^duxrdh$4pu8-q5vkba2yf$ptd1lev_'
above line didn't give the error
In my case, while setting up a Github action I just forgot to add the env variables to the yml file:
jobs:
build:
env:
VAR1: 1
VAR2: 5
In my case, after a long search I found that PyCharm in your Django settings (Settings > Languages & Frameworks > Django) had the configuration file field undefined. You should make this field point to your project's settings file. Then, you must open the Run / Debug settings and remove the environment variable DJANGO_SETTINGS_MODULE = existing path.
This happens because the Django plugin in PyCharm forces the configuration of the framework. So there is no point in configuring any os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings')
Import base.py in __init__.py alone. make sure you won't repeat the same configuration again!.
set environment variable
SET DJANGO_DEVELOPMENT =dev
settings/
__init__.py
base.py
local.py
production.py
In __init__.py
from .base import *
if os.environ.get('DJANGO_DEVELOPMENT')=='prod':
from .production import *
else:
from .local import *
In base.py configured the global configurations. except for Database. like
SECRET_KEY, ALLOWED_HOSTS,INSTALLED_APPS,MIDDLEWARE .. etc....
In local.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'database',
'USER': 'postgres',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '5432',
}
}
I came here looking for answer as I was facing the same issues, none of the answers here worked for me. Then after searching in other websites i stumbled upon this simple fix. It worked for me
wsgi.py
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yourProject.settings')
to
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yourProject.settings.dev')
Let me share m interesting solution!
I put the
SECRET_KEY = "***&^%$#" in settings packages init.py file and the error disappeared! it's actually a loading problem!
Hope this quick workaround is useful for some of you!
try import django then run django.setup() after the secret_key definition. like so:
SECRET_KEY = 'it5bs))q6toz-1gwf(+j+f9#rd8%_-0nx)p-2!egr*y1o51=45XXCV'
django.setup()
For anyone using Wing IDE: set the DJANGO_SETTINGS_MODULE in your project properties to DJANGO_SETTINGS_MODULE=${DJANGO_SITENAME}.config.settings.development
You will find the settings under: Project --> Project Properties and set the value in the field Environment
(I am using Pycharm, I also tried every solution in here and found out that the solutions works on some codes and some doesn't so I just did this solution)
The easiest Resolution that I did is I deleted the LIB where the installed sitepackages are, opened python interpreter in the settings and then it gave me an option where the program(Pycharm) installed the pip/sitepackges and I reinstalled the rest of the packges for example rest_framewrok etc. in the virtual environment of the project using cmd(or any command prompt tool) and it fixed my problem.
Related
Once I change the DEBUG = False, my site will generate 500 (using wsgi & manage.py runserver), and there is no error info in Apache error log and it will run normally when I change debug to True .
I'm using Django 1.5 & Python 2.7.3
here is Apache access log and without any log in apache error log
www.beta800.net:80 222.247.56.11 - - [28/Feb/2013:13:42:28 +0800] "GET / HTTP/1.1" 500 257 "-" "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22"
www.beta800.net:80 222.247.56.11 - - [28/Feb/2013:13:42:28 +0800] "GET /favicon.ico HTTP/1.1" 500 257 "-" "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22"
www.beta800.net:80 222.247.56.11 - - [28/Feb/2013:13:42:28 +0800] "GET /favicon.ico HTTP/1.1" 500 257 "-" "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22"
Here is my settings file:
import os.path
DEBUG = False
#TEMPLATE_DEBUG = DEBUG
HERE = os.path.dirname(__file__)
ADMINS = (
('admin', 'xyzadmin#qq.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'zdm', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': 'passwd', # 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.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
#STATIC_ROOT = os.path.join(HERE, 'static').replace('\\','/')
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
#STATIC_ROOT = os.path.join(HERE, 'static').replace('\\','/')
S= os.path.join(HERE, 'static').replace('\\','/')
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'/home/zdm/static',
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '9a7!^gp8ojyk-^^d#*whuw!0rml+r+uaie4ur$(do9zz_6!hy0'
# 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 = 'zdm.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'zdm.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.
'/home/zdm/templates',
)
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',
'zdm',
'portal',
'admin',
'tagging',
)
Django 1.5 introduced the allowed hosts setting that is required for security reasons. A settings file created with Django 1.5 has this new section which you need to add:
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.9/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
Add your host here like ['www.beta800.net'] or ['*'] for a quick test, but don't use ['*'] for production.
I know this is late but I ended up here with a search for my error 500 with DEBUG=False, in my case it did turn out to be the ALLOWED_HOSTS but I was using os.environ.get('variable') to populate the hosts, I did not notice this until I enabled logging, you can log all errors to file with the below and it will log even when DEBUG=False:
# settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt' : "%d/%b/%Y %H:%M:%S"
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'mysite.log',
'formatter': 'verbose'
},
},
'loggers': {
'django': {
'handlers':['file'],
'propagate': True,
'level':'DEBUG',
},
'MYAPP': {
'handlers': ['file'],
'level': 'DEBUG',
},
}
}
I encountered the same issue just recently in Django 2.0. I was able to figure out the problem by setting DEBUG_PROPAGATE_EXCEPTIONS = True. See here: https://docs.djangoproject.com/en/2.0/ref/settings/#debug-propagate-exceptions
In my case, the error was ValueError: Missing staticfiles manifest entry for 'admin/css/base.css'. I fixed that by locally running python manage.py collectstatic.
In my case, reading docs of third party apps properly saved me.
The culprit? django_compressor
I had
{% load compress %}
{% compress css %}
... css files linked here ..
{% endcompress %}
DEBUG = True always gave me 500. To fix it, I needed a line in my settings to get it running
COMPRESS_ENABLED = os.environ.get('COMPRESS_ENABLED', False)
Its mid 2019 and I faced this error after a few years of developing with Django. Baffled me for an entire night! It wasn't allowed host (which should throw a 400), everything else checked out, finally did some error logging only to discover that some missing / or messed up static files manifest (after collectstatic) were screwing with the setup. Long story short, for those who are stumped AND SO HAPPEN ARE USING WHITENOISE OR THE DJANGO STATICFILE BACKEND WITH CACHE (manifest static files) , maybe this is for you.
Make sure you setup everything (as I did for the whitenoise backend...django backends read on nonetheless) http://whitenoise.evans.io/en/stable/django.html
If error code 500 still shoots you down, take note on your settings.STATICFILES_STORAGE.
Set it to either (for whitenoise backend with compression)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
or (leave as django default)
STATICFILES_STORAGE = django.contrib.staticfiles.storage.StaticFilesStorage
All in all, THE PROBLEM seemed to come from the fact that this whitenoise cache + compression backend -->
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
or the django's own caching backend -->
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
...didnt quite work well for me, since my css was referencing some other sources which may be mixed up during collectstatic / backend caching. This issue is also potentially highlighted in http://whitenoise.evans.io/en/stable/django.html#storage-troubleshoot
Right, in Django 1.5 if DEBUG = False, configure ALLOWED_HOSTS, adding domains without the port number. example:
ALLOWED_HOSTS = ['localhost']
You must also check your URLs all over the place. When the DEBUG is set to False, all URLs without trailing / are treated as a bug, unlike when you have DEBUG = True, in which case Django will append / everywhere it is missing. So, in short, make sure all links end with a slash EVERYWHERE.
Complementing the main answer
It is annoying to change the ALLOWED_HOSTS and DEBUG global constants in settings.py when switching between development and production.
I am using this code to set these setting automatically:
import socket
if socket.gethostname() == "server_name":
DEBUG = False
ALLOWED_HOSTS = [".your_domain_name.com",]
...
else:
DEBUG = True
ALLOWED_HOSTS = ["localhost", "127.0.0.1",]
...
If you use macOS you could write a more generic code:
if socket.gethostname().endswith(".local"): # True in your local computer
DEBUG = True
ALLOWED_HOSTS = ["localhost", "127.0.0.1",]
else:
...
For what it's worth - I was getting a 500 with DEBUG = False on some pages only. Tracing back the exception with pdb revealed a missing asset (I suspect the {% static ... %} template tag was the culprit for the 500.
ALLOWED_HOSTS is NOT the only issue, for me I had to make a 404.html and put it in the base level of my templates (not app level) - Also, you can make a 404 view and add a 404handler url but I think thats optional. 404.html fixed it
in mainproject.urls
handler404 = 'app.views.custom_404'
in app.views
def custom_404(request):
return render(request, '404.html', {}, status=404)
then make a templates/404.html template
got this from another S/O post that I cannot find it
EDIT
also, I get 500 errors when I serve assets with whitenoise. Could not figure that out for the life of me, error was ValueError from whitenoise not being able to find an asset that I also could not find, had to go with default django serving for now
I have a hilarious story for all. After reaching this page I said "Eureka! I'm saved. That MUST be my problem." So I inserted the required ALLOWED_HOSTS list in setting.py and... nothing. Same old 500 error. And no, it wasn't for lack of a 404.html file.
So for 2 days I busied myself with wild theories, such as that it had something to do with serving static files (understand that I am a noob and noobs don't know what they're doing).
So what was it? It is now Mr. Moderator that we come to a useful tip. Whereas my development Django is version 1.5.something, my production server version is 1.5.something+1... or maybe plus 2. Whatever. And so after I added the ALLOWED_HOSTS to the desktop version of settings.py, which lacked what hwjp requested--- a "default value in settings.py, perhaps with an explanatory comment"--- I did the same on the production server with the proper domain for it.
But I failed to notice that on the production server with the later version of Django there WAS a default value in settings.py with an explanatory comment. It was well below where I made my entry, out of sight on the monitor. And of course the list was empty. Hence my waste of time.
I know that this is a super old question, but maybe I could help some one else. If you are having a 500 error after setting DEBUG=False, you can always run the manage.py runserver in the command line to see any errors that wont appear in any web error logs.
I was searching and testing more about this issue and I realized that static files directories specified in settings.py can be a cause of this, so fist, we need to run this command
python manage.py collectstatic
in settings.py, the code should look something like this:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
I faced the same problem when I did DEBUG = FALSE. Here is a consolidated solution as scattered in answers above and other posts.
By default, in settings.py we have ALLOWED_HOSTS = [] . Here are possible changes you will have to make in ALLOWED_HOSTS value as per scenario to get rid of the error:
1: Your domain name:
ALLOWED_HOSTS = ['www.example.com'] # Your domain name here
2: Your deployed server IP if you don't have domain name yet (which was my case and worked like a charm):
ALLOWED_HOSTS = ['123.123.198.123'] # Enter your IP here
3: If you are testing on local server, you can edit your settings.py or settings_local.py as:
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
4: You can also provide '*' in the ALLOWED_HOSTS value but its not recommended in the production environment due to security reasons:
ALLOWED_HOSTS = ['*'] # Not recommended in production environment
I have also posted a detailed solution on my blog which you may want to refer.
You might want to run python manage.py collectstatic after you set DEBUG = False and ALLOWED_HOSTS = ['127.0.0.1'] in settings.py. After these two steps my web application ran well in my local server even with DEBUG=False mode.
BTW I have these settings in settings.py.
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware', # what i added
'django.middleware.common.CommonMiddleware', # and so on...
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
I assume maybe whitenoise setting has something to do with collectstatic command.
I have the similar issue, in my case it was caused by having a Commented script inside the body tag.
<!--<script> </script>-->
I know this post is quite old but it's still perfectly relevant today.
For what it's worth - I was getting a 500 with DEBUG = False for all pages on my site.
I got no traceback when in debug.
I had to go through every static link in my templates within my site and found one / (forward slash) in front of my image source. {% static ... %}. This caused the 500 error in DEBUG = False but worked perfectly fine in Debug = True with no errors. Very annoying! Be warned! Many hours of time wasted due to a forward slash...
I think it could also be the http server settings. Mine is still broken and had ALLOWED_HOSTS the entire time. I can access it locally (i use gunicorn), but not via the domain name when DEBUG=False. when I try using the domain name it then gives me the error, so makes me think its a nginx related issue.
Here is my conf file for nginx:
server {
listen 80;
server_name localhost myproject.ca www.myproject.ca;
root /var/web/myproject/deli_cms;
# serve directly - analogous for static/staticfiles
location /media/ {
# if asset versioning is used
if ($query_string) {
expires max;
}
}
location /admin/media/ {
# this changes depending on your python version
root /var/web/myproject/lib/python2.6/site-packages/django/contrib;
}
location /static/ {
alias /var/web/myproject/deli_cms/static_root/;
}
location / {
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_connect_timeout 10;
proxy_read_timeout 10;
proxy_pass http://localhost:8000/;
}
# what to serve if upstream is not available or crashes
error_page 500 502 503 504 /media/50x.html;
}
A bit late to the party, and off course there could be a legion of issues but I've had a similar issue and it turned out that I had {% %} special characters inside my html remark...
<!-- <img src="{% static "my_app/myexample.jpg" %}" alt="My image"/> -->
I ran into this issue. Turns out I was including in the template, using the static template tag, a file that did not exist anymore. A look in the logs showed me the problem.
I guess this is just one of many possible reasons for this kind of error.
Moral of the story: always log errors and always check logs.
Thanks to #squarebear, in the log file, I found the error:
ValueError: The file 'myapp/styles.css' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage ...>.
I had a few problems in my django app. I removed the line
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' which I found from the heroku's documentation.
I also had to add extra directory (thanks to another SO answer) static in the root of django application as myapp/static even though I wasn't using it. Then running the command python manage.py collectstatic before running the server solved the problem. Finally, it started working fine.
this maybe help someone else, in my case the problem with the missing favicon.
I know this is an old question, but I was also getting a 500 error when DEBUG=False. After several hours, I realized I had forgot to end some of the links in my base.html with a trailing slash.
This is old and my problem ended up being related to the problem but not for the OP but my solution is for anyone else who tried the above to no avail.
I had a setting in a modified version of Django to minify CSS and JS files that only ran when DEBUG was off. My server did not have the CSS minifier installed and threw the error. If you are using Django-Mako-Plus, this might be your issue.
One small thing to note, If the array has None in it, then all the subsequent allowed hosts are ignored.
ALLOWED_HOSTS = [
"localhost",
None,
'example.com', # First DNS alias (set up in the app)
#'www.example.com', # Second DNS alias (set up in the app)
]
Django version 1.8.4
I had one view that threw a 500 error in debug=false but worked in debug=true. For anyone who is getting this kind of thing and Allowed Hosts is not the problem, I fixed my view by updating a template's static tag that was pointing to the wrong location.
So I'd suggest just checking links and tags are airtight in any templates used, maybe certain things slip through the net in debug but give errors in production.
I found yet another cause of the 500 error when DEBUG=False. I use the Django compressor utility and our front-end engineer added references to font files inside a compress css block in a Django template. Like this:
{% compress css %}
<link href="{% static "css/bootstrap.css" %}" rel="stylesheet">
<link href="{% static "css/bootstrap-spinedit.css" %}" rel="stylesheet">
<link href="{% static "djangular/css/styles.css" %}" rel="stylesheet">
<link href="{% static "fonts/fontawesome-webfont.ttf" %}" rel="stylesheet">
{% endcompress %}
The solution was to move the link to the ttf file below the endcompress line.
I started to get the 500 for debug=False in the form of
django.urls.exceptions.NoReverseMatch: Reverse for 'home' not found.
or...
django.urls.exceptions.NoReverseMatch: Reverse for 'about' not found.
when raising django.core.exceptions.ValidationError instead of raising rest_framework.serializers.ValidationError
To be fair, it was already raising a 500 before, but as a ValidationError, with debug=False, this changed into the NoReverseMatch.
I had a problem similar to this and I will report how I solved mine because it could be that someone is also experiencing the same.
In my case, the error was caused because the server was not finding some static files from the homepage.
So make sure the error only occurs in the index or occurs on another page. If the problem is only occurring in the index very probably you need to check the static files. I recommend opening the Chrome preview console and checking for any errors.
In my case, the server couldn't find favicon.ico and two other CSS.
To fix this I passed python manage.py collectstatic and it worked.
my problem was in wrong 404.html template - I copy&pasted
<a href="{% url 'home:index' %}">
instead of (in my case)
<a href="{% url 'posts:index' %}">
that's why 500 apperar
new to web dev here. I'm trying to run a really basic web application using the djangoappengine fork of django nonrel 1.6. I'm running it locally, but the logging doesn't work. Here's the error:
python manage.py runserver
INFO 2015-07-07 18:22:18,926 sdk_update_checker.py:229] Checking for updates to the SDK.
INFO 2015-07-07 18:22:19,157 sdk_update_checker.py:257] The SDK is up to date.
INFO 2015-07-07 18:22:19,218 api_server.py:204] Starting API server at: http://localhost:51763
INFO 2015-07-07 18:22:19,225 dispatcher.py:197] Starting module "default" running at: http://127.0.0.1:8080
INFO 2015-07-07 18:22:19,226 admin_server.py:118] Starting admin server at: http://localhost:8000
ERROR 2015-07-07 18:22:22,080 wsgi.py:263]
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 96, in LoadObject
__import__(cumulative_path)
File "/Users/prog/Desktop/djangoNonRel/project2/djangoappengine/main/__init__.py", line 37, in <module>
setup_env(settings.DEV_APPSERVER_VERSION)
File "/Users/prog/Desktop/djangoNonRel/project2/django/conf/__init__.py", line 54, in __getattr__
self._setup(name)
File "/Users/prog/Desktop/djangoNonRel/project2/django/conf/__init__.py", line 50, in _setup
self._configure_logging()
File "/Users/prog/Desktop/djangoNonRel/project2/django/conf/__init__.py", line 80, in _configure_logging
logging_config_func(self.LOGGING)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/config.py", line 794, in dictConfig
dictConfigClass(config).configure()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/config.py", line 576, in configure
'%r: %s' % (name, e))
ValueError: Unable to configure handler 'file': [Errno 30] Read-only file system: '/Users/prog/Documents/guestbook.log'
INFO 2015-07-07 18:22:22,086 module.py:812] default: "GET /_ah/warmup HTTP/1.1" 500 -
The server continues to run, but as you can see, I can't write to the log that is being generated. I've tried these fixes so far:
-used chmod 755 and 777 to change the permissions on the full path
-changed the path to the current one(old one was creating the log in my project folder)
-used chmod 755 and 777 to change the permissions on the new full path
Here's my setting.py code:
# Django settings for myapp project.
# Initialize App Engine and import the default settings (DB backend, etc.).
# If you want to use a different backend you have to remove all occurences
# of "djangoappengine" from this file.
from djangoappengine.settings_base import *
import os
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
# Activate django-dbindexer for the default database
DATABASES['default'] = {'ENGINE': 'dbindexer', 'TARGET': DATABASES['default']}
AUTOLOAD_SITECONF = 'indexes'
# Hosts/domain names that are valid for this site; required if DEBUG is False
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = False
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'ilpeey9j&dk#4u5gx!iv)0hnxm*eu=nfpmvn92!n)+mc3#q0t5'
# 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 = (
# This loads the index definitions, so it has to come first
'autoload.middleware.AutoloadMiddleware',
'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',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.request'
)
LOGIN_REDIRECT_URL = '/guestbook/'
ADMIN_MEDIA_PREFIX = '/media/admin/'
ROOT_URLCONF = 'urls'
TEMPLATE_DIRS = (
'/Users/prog/Desktop/djangoNonRel/project2/templates/guestbook/',
# 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',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'djangotoolbox',
'autoload',
'dbindexer',
'guestbook',
# djangoappengine should come last, so it can override a few manage.py commands
'djangoappengine',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt' : "%d/%b/%Y %H:%M:%S"
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': '/Users/prog/Documents/guestbook.log',
'formatter': 'verbose'
},
},
'loggers': {
'django': {
'handlers':['file'],
'propagate': True,
'level':'DEBUG',
},
'guestbook': {
'handlers': ['file'],
'level': 'DEBUG',
},
}
}
Please let me know if you need anything else from me.
You need to fix permissions with the chmod command
try this command:
chmod 775 /Users/prog/Documents/guestbook.log
I have been tasked to get Gamification up and running in our department to motivate the staff.
I found this https://github.com/ngageoint/gamification-server which is an opensource gamification server released by the NGA.
I have followed all the instructions to the letter but cant get the server up.
Some Info:
Platform - Ubuntu 14 LTS
Packages Installed Before Getting Started on Gamification:
PostgreSQL
Python Python-dev
Git
Virtualenv
I am able to install the dependencies but when i go to the second task "paver createdb" I get the following error:
---> pavement.createdb
Captured Task Output:
---------------------
---> pavement.createdb
Traceback (most recent call last):
File "/root/pyenv/gamification/local/lib/python2.7/site-packages/paver/tasks.p y", line 195, in _run_task
return do_task()
File "/root/pyenv/gamification/local/lib/python2.7/site-packages/paver/tasks.p y", line 192, in do_task
return func(**kw)
File "pavement.py", line 87, in createdb
from gamification import settings
File "/etc/gamification-server/gamification/__init__.py", line 3, in <module>
from gamification.core.models import Points
File "/etc/gamification-server/gamification/core/models.py", line 27, in <modu le>
from django.contrib.auth.models import User
File "/root/pyenv/gamification/local/lib/python2.7/site-packages/django/contri b/auth/__init__.py", line 7, in <module>
from django.middleware.csrf import rotate_token
File "/root/pyenv/gamification/local/lib/python2.7/site-packages/django/middle ware/csrf.py", line 14, in <module>
from django.utils.cache import patch_vary_headers
File "/root/pyenv/gamification/local/lib/python2.7/site-packages/django/utils/ cache.py", line 26, in <module>
from django.core.cache import caches
File "/root/pyenv/gamification/local/lib/python2.7/site-packages/django/core/c ache/__init__.py", line 34, in <module>
if DEFAULT_CACHE_ALIAS not in settings.CACHES:
File "/root/pyenv/gamification/local/lib/python2.7/site-packages/django/conf/_ _init__.py", line 48, in __getattr__
self._setup(name)
File "/root/pyenv/gamification/local/lib/python2.7/site-packages/django/conf/_ _init__.py", line 42, in _setup
% (desc, ENVIRONMENT_VARIABLE))
ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
I have configured the settings.py file as per instruction and installed all packages and dependencies as required but getting absolutely nowhere.
Settings.py
import os
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = [
# ("Your Name", "your_email#example.com"),
]
MANAGERS = ADMINS
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": "gamification",
"USER": "game_manager",
"PASSWORD": "django-gamification",
"HOST": "localhost",
"PORT": "5432"
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = "UTC"
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = "en-us"
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
#MEDIA_ROOT = os.path.join(PACKAGE_ROOT, "site_media", "media")
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
# MEDIA_URL = "/site_media/media/"
# Absolute path to the directory static files should be collected to.
# Don"t put anything in this directory yourself; store your static files
# in apps" "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
#STATIC_ROOT = '{0}'.format('/var/www/static')
STATIC_ROOT = os.path.join(PACKAGE_ROOT, "static")
MEDIA_ROOT = os.path.join(PROJECT_ROOT, "gamification/site_media")
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = "/static/"
# Additional locations of static files
#STATICFILES_DIRS = [
# os.path.join(PACKAGE_ROOT, "static"),
#]
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]
# Make this unique, and don't share it with anybody.
SECRET_KEY = "z7lz3v!zl9yohg2(yfk0!cmv)#lkl6znja*hh877b&byujuu7875vfr"
# 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",
]
TEMPLATE_CONTEXT_PROCESSORS = [
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.core.context_processors.request",
"django.contrib.messages.context_processors.messages",
"account.context_processors.account",
"pinax_theme_bootstrap.context_processors.theme",
]
MIDDLEWARE_CLASSES = [
"django.middleware.common.CommonMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"corsheaders.middleware.CorsMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
]
ROOT_URLCONF = "gamification.urls"
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = "gamification.wsgi.application"
TEMPLATE_DIRS = [
os.path.join(PACKAGE_ROOT, "templates"),
]
REST_FRAMEWORK = {
# hyperlinked styles by default
# only used if the 'serializer_class' attribute is not set on view
'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.serializers.HyperlinkedModelSerializer',
# Use Django's standard 'django.contrib.auth' permissions, or read-only for unauthorized users
# 'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly']
}
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.sites",
"django.contrib.messages",
"django.contrib.staticfiles",
# theme
"pinax_theme_bootstrap",
"django_forms_bootstrap",
# external
"account",
"metron",
"eventlog",
"bootstrap3",
"south",
"rest_framework",
"corsheaders",
"mptt",
# project
"gamification",
"gamification.badges",
"gamification.core",
"gamification.events",
]
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
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,
},
}
}
FIXTURE_DIRS = [
os.path.join(PROJECT_ROOT, "fixtures"),
]
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
ACCOUNT_OPEN_SIGNUP = True
ACCOUNT_USE_OPENID = False
ACCOUNT_REQUIRED_EMAIL = False
ACCOUNT_EMAIL_VERIFICATION = False
ACCOUNT_EMAIL_AUTHENTICATION = False
ACCOUNT_LOGIN_REDIRECT_URL = "home"
ACCOUNT_LOGOUT_REDIRECT_URL = "home"
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 2
AUTHENTICATION_BACKENDS = [
"account.auth_backends.UsernameAuthenticationBackend",
]
CORS_ORIGIN_WHITELIST = ( '192.168.5.131:8000', 'localhost:8000', )
CORS_ALLOW_METHODS = ( 'GET', 'POST', 'OPTIONS' )
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
UPDATE -- For anyone that finds this code and struggles with the same thing.
In the pavement.py file under the task createdb and create_db_user i added the following 2 lines
import os
os.environ["DJANGO_SETTINGS_MODULE"]="gamification.settings"
--UPDATE--
Finally got the thing to work. Seems there are a couple steps missing in the setup of the gamification server.
Before issuing Paver createdb I ran paver install_fixture and paver sync_initial this sorted it out for me and the server is now running perfectly
Ok i manage to resolve this matter myself. If anyone finds this code and wants to use it as a gamification server follow the below steps:
Setup your OS (I used Linux Ubuntu)
Install python, postgresql, git, pip, libpq-dev
Create and Activate virtual env
Clone the code to your cwd
Install Paver
Install Dependencies
run command paver sync_initial, paver install_fixture
Paver createdb
Paver create_db_user
python manage.py createsuperuser
python manage.py runserver
That should get things up and going. See my original post for the changes i made to some of the files which would also help in setting up the server correctly.
After playing around with the commands above, I was still having trouble creating the database, user and tables with the createdb and create_db_user commands. So, I started thinking that maybe it was a permissions issue.
The following helped me get the database populated (note that this may be obvious to most, but just wasn't for me).
These steps are for Ubuntu, but I think they will work on other Linux types as long as Postgres 8.x or greater, Python2.7 and the VirtualEnv are installed and working.
Login into Postgres:
$ bash #=> run under bash if not already
$ export DJANGO_SETTINGS_MODULE="gamification.settings"
$ source ~/pyenv/gamification/bin/activate
$ sudo service postgresql start
$ psql -U postgres
postgres-# CREATE USER game_manager WITH PASSWORD 'supersecret';
postgres-# CREATE DATABASE gamification;
postgres=# GRANT ALL PRIVILEGES ON DATABASE gamification to game_manager;
postgres-# ALTER USER GRANT SELECT ON gamification to game_manager;
postgres-# ALTER USER GRANT INSERT ON gamification to game_manager;
postgres-# ALTER USER GRANT DELETE ON gamification to game_manager;
postgres-# ALTER USER GRANT RULE ON gamification to game_manager;
postgres=# GRANT ALL PRIVILEGES ON table-name to public; #=> this step may be unnecessary
$ python manage.py syncdb
$ python manage.py syncdb #=> run it again
$ python manage.py migrate gamification.core
$ python manage.py migrate gamification.badges
$ python manage.py migrate gamification.event
$ python manage.py migrate gamification.core #=> run it again
$ python manage.py migrate gamification.badges #=> run it again
$ python manage.py migrate gamification.events #=> run it again
Disregard errors. They are (I think) because of the circular dependencies mentioned in the post above.
Update
Looking closely at the stacktrace there seems to be circular-reference to import the settings.
The createdb task imports settings >> the gamification (the init py file) imports core.models >> which imports the django User >> causes the settings to be imported to look for DEFAULT_CACHE_ALIAS ...
I think you better look at whether this is a stable build of the Gamification Server package.
Original answer:
The full error is:
ImproperlyConfigured: Requested setting CACHES, but settings are not
configured. You must either define the environment variable
DJANGO_SETTINGS_MODULE or call settings.configure() before accessing
settings.
Django (1.8) has the CACHES setting pre-set with the required 'default' backend. So for vanilla Django it works straight up with no CACHES setting declared.
To me the error implies the Django settings object isn't initialised. It's possible that the settings.py hasn't been loaded (possible if paver createdb isn't a Django management command).
Occasionally I've found this type of error when my settings.py has a syntax error and isn't being parsed properly by the interpreter. You can try using the python shell and running "import settings.py" to check it directly.
I am trying to connect the settings.py database engine to the clearDB using Heroku as my service to launch, and when I enter in the terminal python manage.py syncdb, I keep receiving an error message:
ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.
Without this step I cannot comfortable start using Heroku and adding information to my database, so any suggestions as to how and fix this error? ( I am using python *just adding additional information)
Here is my settings.py:
# Django settings for indieitude project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # 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.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '9wha-70a!)zowq5(e4pxoa5uxv0(#e%dcv$1^xela9(b+#npi6'
# 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 = 'indieitude.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'indieitude.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',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
#Apps for Concepteur Market
'designers',
'boutiques',
'profiles',
'products',
#Third Party Apps
)
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
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,
},
}
}
######### Heroku Environment #########
# Parse database configuration from $DATABASE_URL
import dj_database_url
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')
# Allow all host headers
ALLOWED_HOSTS = ['*']
# Static asset configuration
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Here is my directory structure:
venv: is the virtual environment (so anyone on the team can use and activate the environment easily)
indieitude-project/indieitude directory: Has all of my django applications and files
indieitude-project/indieitude/indieitude directory: has all the config files i.e. settings, urls.py etc
I have created a production_settings.py in which I am putting all the production env variables and values eg:
import dj_database_url
DATABASES['default'] = dj_database_url.config()
I thought I'd declare an env variable like
MYPROJECT_PRODUCTION
and set this like
heroku config:add MYPROJECT_PRODUCTION=True or export MYPROJECT_PRODUCTION=True
In the settings.py (which is the default created by django) ,I thought I'd add at the end of the file
import os
if os.environ.has_key('MYPROJECT_PRODUCTION') and os.environ.get('MYPROJECT_PRODUCTION')=='True':
from production_settings import *
Is this the correct way of doing this?
I am getting an import error when I try python manage shell
export DJANGO_SETTINGS_MODULE='myproject.settings'
export MYPROJECT_PRODUCTION=True
me#ubuntu:~/dev/python/django/myproject$ python manage.py shell
Error: Can't find the file 'settings.py' in the directory containing 'manage.py'. It appears you've customized things.
You'll have to run django-admin.py, passing it your settings module.
(If the file settings.py does indeed exist, it's causing an ImportError somehow.)
the manage.py exists in the same folder as settings.py ..still the error occurs.
I checked echo $MYPROJECT_PRODUCTION which outputs True
Personally, I keep my production settings in settings.py then include a local_settings.py file (that's excluded from revision control with .hgignore).
I add the following to the end of settings.py
try:
from local_settings import *
except ImportError, e:
pass
Then in my local_settings.py I override the appropriate settings -
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'tag',
'USER': 'tag',
'PASSWORD': 'tag',
'HOST': 'localhost',
'PORT': '5432',
}
}
I'm under the impression that this is a fairly well used method (I picked it up from colleagues but I've seen it blogged about too)
EDIT
In response to balazs very good point you might include a variation on this method, in order to keep sensitive data private. Perhaps include the following after the local_settings import -
try:
from production_settings import *
except ImportError, e:
pass
Then exclude production_settings.py from version control. I guess you may need to use a different method to deploy production_settings.py, but I don't suppose that's too big a deal.
I advise against using different settings files for different environments in favour of customising your settings with environment variables. This allows you by default to use your local development settings and override it in production.
For example database and static / media root settings
# Default database URL is a local SQLite instance
DATABASE_URL = 'sqlite:///%s' % os.path.join(os.path.dirname(__file__), 'db.sqlite')
DATABASES = {
'default': dj_database_url.config('DATABASE_URL', default=DATABASE_URL),
}
MEDIA_ROOT = os.environ.get('MEDIA_ROOT',
os.path.join(os.path.dirname(__file__), 'media'))
MEDIA_URL = os.environ.get('MEDIA_URL', '/media/')
STATIC_ROOT = os.environ.get('STATIC_ROOT',
os.path.join(os.path.dirname(__file__), 'static'))
STATIC_URL = os.environ.get('STATIC_URL', '/static/')
This allows you to set any setting on Heroku via heroku config:set and removes the complexity of dealing with multiple settings files, for example:
heroku config:set MEDIA_URL=http://custom-media-server.com/media/
heroku config:set STATIC_URL=http://custom-media-server.com/static/
I have also created a custom Django project template that can take most settings from environment variables.
You should also look at the 12 Factor Application website and specifically at how to store configuration.
Have you defined DATABASES as a dictionary? by:
DATABASES = {}
also show your heroku logs