Django:错误地configuration:SECRET_KEY设置不能为空

我正在尝试设置包含一些基本设置的多个设置文件(开发,生产,..)。 虽然不能成功。 当我尝试运行./manage.py runserver时出现以下错误:

 (cb)clime@den /srv/www/cb $ ./manage.py runserver ImproperlyConfigured: The SECRET_KEY setting must not be empty. 

这是我的设置模块:

 (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 

基本设置(包含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&amp;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' 

其中一个设置文件:

 (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', ) 

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) 

如果我from base import *添加到/ /srv/www/cb/cb/settings/__init__.py (否则为空),它神奇地开始工作,但我不明白为什么。 任何人都可以向我解释这是怎么回事? 这一定是一些python模块的魔力。

编辑:一切也开始工作,如果我从base.py中删除此行

 django.template.loader.add_to_builtins('web.templatetags.cb_tags') 

如果我从web.templatetags.cb_tags中删除这行,它也开始工作:

 from endless_pagination.templatetags import endless 

我想这是因为它最终导致了

 from django.conf import settings PER_PAGE = getattr(settings, 'ENDLESS_PAGINATION_PER_PAGE', 10) 

所以它创造了一些怪异的循环的东西和游戏结束。

我有同样的错误,结果是由设置和设置模块本身加载的东西之间的循环依赖。 在我的情况下,这是一个中间件类,它是在自己试图加载设置的设置中命名的。

根据Daniel Greenfield的书“Django Two scoops”的说明重新设置后,我遇到了同样的问题。

我通过设置解决了这个问题

 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings.local") 

manage.pywsgi.py

我有与python manage.py runserver相同的错误。

对我来说,原来是因为一个陈旧的编译二进制(.pyc)文件。 删除我的项目中的所有这些文件后,服​​务器再次开始运行。 🙂

所以如果你从这个地方得到这个错误,也就是说,没有任何与Django设置相关的变化,这可能是一个很好的第一个措施。

删除.pyc文件

Ubuntuterminal命令删除.pyc: find . -name "*.pyc" -exec rm -rf {} \; find . -name "*.pyc" -exec rm -rf {} \;

当我做了python manage.py runserver时,我得到了同样的错误。 这是因为.pyc文件。 我从项目目录删除.pyc文件,然后它工作。

它开始工作,因为在base.py你有一个基本的设置文件所需的所有信息。 你需要这行:

 SECRET_KEY = '8lu*6g0lg)9z!ba+a$ehk)xt)x%rxgb$i1&amp;022shmi1jcgihb*' 

所以它工作,当你from base import * ,它importSECRET_KEY到您的development.py

进行任何自定义设置之前,您应该始终导入基本设置。


编辑:另外,当django从你的包中导入开发时,它会初始化base中的所有variables,因为你已经from base import *里面定义from base import * __init__.py

我解决了在使用Django 1.5和1.6的OS X上发生的这个问题,通过禁用所有活动会话到virtualenv并重新启动它。

我认为这是环境错误 ,你应该尝试设置: DJANGO_SETTINGS_MODULE='correctly_settings'

我没有指定设置文件:

 python manage.py runserver --settings=my_project.settings.develop 

我只是想补充说,当我的数据库名称拼写错误在我的settings.py文件,所以无法创build数据库时,我得到了这个错误。

我在1.8.4上解决了这个问题,通过修改了一个有拼写错误的TEMPLATES设置(删除了TEMPLATES ['debug']解决了这个问题)

仔细阅读最近更改的设置,确保所有的密钥都是通过书本。

我通过删除我的.env文件中等号( = )的空格解决了这个问题。

为了将另一个潜在的解决scheme引入混合,我有一个settings文件夹以及我的项目目录中的settings.py 。 (我从基于环境的设置文件切换到一个文件,我已经重新考虑了。)

Python对我是否想导入project/settings.py或者project/settings/__init__.py 。 我删除了settings目录,现在一切正常。