Django:NotperlyConfigured:SECRET_KEY设置不能为空

问题描述 投票:73回答:18

我正在尝试设置包含一些基本设置的多个设置文件(开发,生产,...)。虽然不能成功。当我尝试运行./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', '[email protected]'),
)

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'

其中一个设置文件:

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

所以它创造了一些奇怪的循环内容和游戏结束。

python django settings
18个回答
82
投票

我有同样的错误,结果是由设置和设置模块本身加载的模块或类之间的循环依赖。在我的例子中,它是一个中间件类,它在设置中命名,它本身试图加载设置。


2
投票

在settings目录的init.py中写入正确的import,如:

from Project.settings.base import *

无需更改wsgi.py或manage.py


1
投票

我只是想补充说,当我的settings.py文件中的数据库名称拼写错误时,我收到此错误,因此无法创建数据库。


1
投票

我通过修复有错字的TEMPLATES设置解决了这个问题(删除了TEMPLATES ['debug']解决了它)

查看最近更改过的设置,确保所有按键均为按书。


1
投票

对于任何使用PyCharm的人:绿色的“运行选定的配置”按钮会产生错误,同时运行py manage.py runserver 127.0.0.1:8000 --settings=app_name.settings.development会起作用。

要解决此问题,您需要编辑配置的环境变量。要执行此操作,请单击绿色运行按钮左侧的“选择运行/调试配置”下拉菜单,然后单击“编辑配置”。在“环境”选项卡下,将环境变量DJANGO_SETTINGS_MODULE更改为app_name.settings.development


0
投票

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


0
投票

为了在混合中投入另一个潜在的解决方案,我在项目目录中有一个settings文件夹和一个settings.py。 (我正在从基于环境的设置文件切换回一个文件。我已经重新考虑了。)

Python对我是否要导入project/settings.pyproject/settings/__init__.py感到困惑。我删除了settings目录,现在一切正常。


0
投票

在我的情况下问题是 - 我有我的app_foldersettings.py。然后我决定在Settings folder里面制作app_folder - 这与settings.py发生了碰撞。刚重命名为Settings folder - 一切正常。


0
投票

我的Mac OS不喜欢它没有在设置文件中找到env变量集:

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('MY_SERVER_ENV_VAR_NAME')

但在将env var添加到我的本地Mac OS开发环境后,错误消失了:

export MY_SERVER_ENV_VAR_NAME ='fake dev security key that is longer than 50 characters.'

在我的情况下,我还需要添加--settings param:

python3 manage.py check --deploy --settings myappname.settings.production

其中production.py是包含设置文件夹内的生产特定设置的文件。


0
投票

我的问题是在LANGUAGES中可以调用get_text_noop

更改

LANGUAGES = (
    ('en-gb', get_text_noop('British English')),
    ('fr', get_text_noop('French')),
)

from django.utils.translation import gettext_lazy as _

LANGUAGES = (
    ('en-gb', _('British English')),
    ('fr', _('French')),
)

在基本设置文件中解析了ImproperlyConfigured: The SECRET_KEY setting must not be empty异常。


55
投票

根据丹尼尔格林菲尔德的书“两勺Django”的说明重组设置后,我遇到了同样的问题。

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

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

manage.pywsgi.py


17
投票

我和python manage.py runserver有同样的错误。

对我来说,事实证明这是因为过时的编译二进制(.pyc)文件。删除项目中的所有此类文件后,服​​务器再次开始运行。 :)

因此,如果你不知从哪里得到这个错误,即没有做任何看似与django-settings相关的改变,这可能是一个很好的第一个措施。


12
投票

删除.pyc文件

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

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


6
投票

它开始工作,因为在base.py上,您拥有基本设置文件中所需的所有信息。你需要这条线:

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

所以它有效,当你做from base import *时,它会将SECRET_KEY导入你的development.py

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


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


5
投票

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


5
投票

我没有指定设置文件:

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

2
投票

我通过停用所有活动会话到virtualenv并再次启动它来解决在X和Django 1.5和1.6上发生的问题。


2
投票

我和芹菜有同样的问题。我的setting.py之前:

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')

后:

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', <YOUR developing key>)

如果未定义环境变量,则:SECRET_KEY =您的开发密钥

© www.soinside.com 2019 - 2024. All rights reserved.