Django:ImproperlyConfigured:SECRET_KEY 设置不能为空 [英] Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

查看:31
本文介绍了Django:ImproperlyConfigured:SECRET_KEY 设置不能为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

(cb)clime@den/srv/www/cb $ ./manage.py runserverImproperlyConfigured:SECRET_KEY 设置不能为空.

这是我的设置模块:

(cb)clime@den/srv/www/cb/cb/settings $ ll共 24 个-rw-rw-r--.1 气候气候 8230 Oct 2 02:56 base.py-rw-rw-r--.1 气候气候 489 Oct 2 03:09 development.py-rw-rw-r--.1 气候气候 24 Oct 2 02:34 __init__.py-rw-rw-r--.1 气候气候 471 Oct 2 02:51 production.py

基本设置(包含 SECRET_KEY):

(cb)clime@den/srv/www/cb/cb/settings $ cat base.py:# cb 项目的 Django 基本设置.导入 django.conf.global_settings 作为默认值调试 = 错误TEMPLATE_DEBUG = 假INTERNAL_IPS = ('127.0.0.1',)管理员 = (('clime', 'clime7@gmail.com'),)经理 = 管理员数据库 = {'默认': {#'ENGINE': 'django.db.backends.postgresql_psycopg2', # 添加 'postgresql_psycopg2'、'mysql'、'sqlite3' 或 'oracle'.'引擎':'django.db.backends.postgresql_psycopg2','NAME': 'cwu', # 如果使用 sqlite3,则为数据库文件的路径.'USER': 'clime', # 不用于 sqlite3.'PASSWORD': '', # 不用于 sqlite3.'HOST': '', # 设置为 localhost 的空字符串.不与 sqlite3 一起使用.'PORT': '', # 默认设置为空字符串.不与 sqlite3 一起使用.}}# 此安装的本地时区.选择可以在这里找到:# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name# 虽然并非所有选项都适用于所有操作系统.# 在 Windows 环境中,这必须设置为您的系统时区.TIME_ZONE = '欧洲/布拉格'# 此安装的语言代码.所有选择都可以在这里找到:# http://www.i18nguy.com/unicode/language-identifiers.htmlLANGUAGE_CODE = 'en-us'SITE_ID = 1# 如果设置为False,Django会做一些优化以免# 加载国际化机制.USE_I18N = 假# 如果你把它设置为 False,Django 将不会格式化日期、数字和# 根据当前区域设置的日历.USE_L10N = False # TODO: 使这个真实的和习惯的日期时间输入DATE_INPUT_FORMATS = defaults.DATE_INPUT_FORMATS + ('%d %b %y', '%d %b, %y') # + ('25 Oct 13', '25 Oct, 13')# 如果您将此设置为 False,Django 将不会使用时区感知日期时间.USE_TZ = 真# 保存用户上传文件的目录的绝对文件系统路径.# 示例:/home/media/media.lawrence.com/media/"MEDIA_ROOT = '/srv/www/cb/media'# 处理从 MEDIA_ROOT 提供的媒体的 URL.确保使用一个# 尾部斜线.# 示例:http://media.lawrence.com/media/"、http://example.com/media/"MEDIA_URL = '/media/'# 静态文件应该收集到的目录的绝对路径.# 不要自己在这个目录下放任何东西;存储您的静态文件# 在应用程序的static/"子目录和 STATICFILES_DIRS 中.# 示例:/home/media/media.lawrence.com/static/"STATIC_ROOT = '/srv/www/cb/static'# 静态文件的 URL 前缀.# 示例:http://media.lawrence.com/static/"STATIC_URL = '/静态/'# 静态文件的附加位置STATICFILES_DIRS = (# 把字符串放在这里,比如/home/html/static"或C:/www/django/static".# 始终使用正斜杠,即使在 Windows 上也是如此.# 不要忘记使用绝对路径,而不是相对路径.)# 知道如何在其中查找静态文件的查找程序类列表# 不同的地点.STATICFILES_FINDERS = ('django.contrib.staticfiles.finders.FileSystemFinder','django.contrib.staticfiles.finders.AppDirectoriesFinder',# 'django.contrib.staticfiles.finders.DefaultStorageFinder',)# 让它独一无二,不要与任何人分享.SECRET_KEY = '8lu*6g0lg)9z!ba+a$ehk)xt)x%rxgb$i1&amp;022shmi1jcgihb*'# 知道如何从各种来源导入模板的可调用列表.模板加载器 = ('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',# 取消注释下一行以进行简单的点击劫持保护:# 'django.middleware.clickjacking.XFrameOptionsMiddleware',)ROOT_URLCONF = 'cb.urls'# Django 运行服务器使用的 WSGI 应用程序的 Python 虚线路径.WSGI_APPLICATION = 'cb.wsgi.application'模板目录 = (# 把字符串放在这里,比如/home/html/django_templates"或C:/www/django/templates".# 始终使用正斜杠,即使在 Windows 上也是如此.# 不要忘记使用绝对路径,而不是相对路径.'/srv/www/cb/web/templates','/srv/www/cb/templates',)安装_应用程序 = ('django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.sites','django.contrib.messages','django.contrib.staticfiles','南','grappelli', # 必须在 admin 之前'django.contrib.admin','django.contrib.admindocs','endless_pagination','调试工具栏','djangoratings','沃森','网络',)AUTH_USER_MODEL = 'web.User'# 一个示例日志配置.唯一有形的伐木# 此配置执行的是发送电子邮件至# 当 DEBUG=False 时,站点管理员会处理每个 HTTP 500 错误.# 见 http://docs.djangoproject.com/en/dev/topics/logging# 有关如何自定义日志记录配置的更多详细信息.日志记录 = {'版本':1,'disable_existing_loggers':错误,过滤器":{'require_debug_false':{'()': 'django.utils.log.RequireDebugFalse'}},格式化程序":{'标准': {'格式' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",'datefmt' : "%d/%b/%Y %H:%M:%S"},},处理程序":{'邮件管理员':{'级别':'错误','过滤器':['require_debug_false'],'类':'django.utils.log.AdminEmailHandler'},'空值': {'级别':'调试','class':'django.utils.log.NullHandler',},'日志文件':{'级别':'调试','class':'logging.handlers.RotatingFileHandler','文件名': "/srv/www/cb/logs/application.log",'maxBytes':50000,'备份计数':2,'格式化程序':'标准',},'安慰':{'级别':'信息','class':'logging.StreamHandler',格式化程序":标准"},},'记录器':{'django.request':{'处理程序':['mail_admins'],'级别':'错误','传播':对,},'django':{'处理程序':['控制台'],'传播':对,'级别':'警告',},'django.db.backends':{'处理程序':['控制台'],'级别':'调试','传播':错误,},'网络':{'处理程序':['控制台','日志文件'],'级别':'调试',},},}LOGIN_URL = '登录'LOGOUT_URL = '退出'#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>

"""DEBUG_TOOLBAR_​​CONFIG = {'INTERCEPT_REDIRECTS':错误,}导入 django.template.loaderdjango.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从基础进口 *调试 = 真TEMPLATE_DEBUG = 真ALLOWED_HOSTS = ['127.0.0.1', '31.31.78.149']数据库 = {'默认': {'引擎':'django.db.backends.postgresql_psycopg2','NAME': 'cwu','用户':'气候','密码': '','主持人': '','港口': '',}}MEDIA_ROOT = '/srv/www/cb/media/'STATIC_ROOT = '/srv/www/cb/static/'模板目录 = ('/srv/www/cb/web/templates','/srv/www/cb/templates',)

manage.py 中的代码:

(cb)clime@den/srv/www/cb $ cat manage.py#!/usr/bin/env python导入操作系统导入系统如果 __name__ == "__main__":os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cb.settings.development")从 django.core.management 导入 execute_from_command_lineexecute_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 无尽分页.templatetags 导入无尽

我猜是因为,最终导致了

from django.conf 导入设置PER_PAGE = getattr(设置,'ENDLESS_PAGINATION_PER_PAGE',10)

因此它创建了一些奇怪的循环内容并结束游戏.

解决方案

我遇到了同样的错误,结果是设置加载的模块或类与设置模块本身之间存在循环依赖关系.在我的例子中,它是一个在设置中命名的中间件类,它本身试图加载设置.

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&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'

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.

这篇关于Django:ImproperlyConfigured:SECRET_KEY 设置不能为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆