Django:经过改进的:SECRET_KEY设置不能为空

时间:2023-01-13 20:55:44

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:

我正在尝试设置多个包含一些基本设置的设置文件(开发、生产、…)。不能成功。当我试着跑的时候。py runserver,我得到以下错误:

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

基础设置(含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:

在jobs代码:

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

如果我从基础导入*进入/srv/www/cb/cb/设置/__init__。py(否则就是空的),它神奇地开始工作,但是我不明白为什么。有人能解释一下这是怎么回事吗?它一定是某种python模块的魔法。

EDIT: Everything also starts to work if I remove this line from base.py

编辑:如果我从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:

如果我从web.templatetags删除这条线。cb_tags也开始工作:

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.

所以它创造了一些奇怪的循环,然后游戏结束。

13 个解决方案

#1


68  

I had the same error and it turned out to be a circular dependency between something 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.

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

#2


46  

I ran into the same problem after restructuring the settings as per the instructions from Daniel Greenfield's book Two scoops of Django.

根据丹尼尔·格林菲尔德(Daniel Greenfield)的《被解救的姜戈》(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.

在管理。py和wsgi.py。

#3


16  

I had the same error with python manage.py runserver.

我对python管理也有同样的错误。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. :)

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

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.

如果你得到这个错误,i。不做任何看起来与django设置相关的改变,这可能是一个很好的第一步。

#4


10  

Remove .pyc files

删除.pyc文件

Ubuntu terminal command for deleting .pyc : find . -name "*.pyc" -exec rm -rf {} \;

用于删除。pyc: find的Ubuntu终端命令。- name”*。-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.

我在做python管理时也犯了同样的错误。py runserver。这是因为。pyc文件。我从项目目录中删除了。pyc文件,然后它就可以工作了。

#5


5  

It starts working because on the base.py you have all information needed in a basic settings file. You need the line:

它开始工作是因为在基地。py在基本设置文件中有所有需要的信息。你需要:

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

So it works and when you do from base import *, it imports SECRET_KEY into your development.py.

所以它是有效的,当你从base导入*时,它会将SECRET_KEY导入到你的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

编辑:而且,当django从包中导入开发时,它会初始化base中的所有变量,因为您是从__init__.py中的base import *中定义的

#6


5  

I hadn't specified the settings file:

我没有指定设置文件:

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

#7


3  

I think that it is the Environment error,you should try setting : DJANGO_SETTINGS_MODULE='correctly_settings'

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

#8


2  

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.

我用Django解决了OS X上出现的这个问题,它使virtualenv的所有活动会话失效,并重新启动它。

#9


1  

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.

我只是想补充一点,当我的数据库名在设置中拼写错误时,我得到了这个错误。py文件,因此无法创建DB。

#10


1  

I solved this problem on 1.8.4 by fixing the TEMPLATES settings which had a typo (removing TEMPLATES['debug'] solved it)

我在1.8.4解决了这个问题,通过修改模板设置(删除模板['debug']解决了这个问题)

Go over the settings that you have changed recently, make sure all keys are by-the-book.

检查你最近更改的设置,确保所有的键都是按顺序排列的。

#11


0  

I solved this problem by removing the spaces around equal signs (=) in my .env file.

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

#12


0  

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.

Python对我是否想导入项目/设置感到困惑。py或项目/设置/ __init__ . py。我删除了settings dir,现在一切正常。

#13


0  

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.

在我的例子中,问题是-我有app_folder和设置。py。然后我决定在app_folder中设置Settings文件夹——这与settings.y发生了冲突。刚刚重命名了设置文件夹——一切都工作了。

#1


68  

I had the same error and it turned out to be a circular dependency between something 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.

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

#2


46  

I ran into the same problem after restructuring the settings as per the instructions from Daniel Greenfield's book Two scoops of Django.

根据丹尼尔·格林菲尔德(Daniel Greenfield)的《被解救的姜戈》(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.

在管理。py和wsgi.py。

#3


16  

I had the same error with python manage.py runserver.

我对python管理也有同样的错误。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. :)

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

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.

如果你得到这个错误,i。不做任何看起来与django设置相关的改变,这可能是一个很好的第一步。

#4


10  

Remove .pyc files

删除.pyc文件

Ubuntu terminal command for deleting .pyc : find . -name "*.pyc" -exec rm -rf {} \;

用于删除。pyc: find的Ubuntu终端命令。- name”*。-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.

我在做python管理时也犯了同样的错误。py runserver。这是因为。pyc文件。我从项目目录中删除了。pyc文件,然后它就可以工作了。

#5


5  

It starts working because on the base.py you have all information needed in a basic settings file. You need the line:

它开始工作是因为在基地。py在基本设置文件中有所有需要的信息。你需要:

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

So it works and when you do from base import *, it imports SECRET_KEY into your development.py.

所以它是有效的,当你从base导入*时,它会将SECRET_KEY导入到你的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

编辑:而且,当django从包中导入开发时,它会初始化base中的所有变量,因为您是从__init__.py中的base import *中定义的

#6


5  

I hadn't specified the settings file:

我没有指定设置文件:

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

#7


3  

I think that it is the Environment error,you should try setting : DJANGO_SETTINGS_MODULE='correctly_settings'

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

#8


2  

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.

我用Django解决了OS X上出现的这个问题,它使virtualenv的所有活动会话失效,并重新启动它。

#9


1  

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.

我只是想补充一点,当我的数据库名在设置中拼写错误时,我得到了这个错误。py文件,因此无法创建DB。

#10


1  

I solved this problem on 1.8.4 by fixing the TEMPLATES settings which had a typo (removing TEMPLATES['debug'] solved it)

我在1.8.4解决了这个问题,通过修改模板设置(删除模板['debug']解决了这个问题)

Go over the settings that you have changed recently, make sure all keys are by-the-book.

检查你最近更改的设置,确保所有的键都是按顺序排列的。

#11


0  

I solved this problem by removing the spaces around equal signs (=) in my .env file.

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

#12


0  

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.

Python对我是否想导入项目/设置感到困惑。py或项目/设置/ __init__ . py。我删除了settings dir,现在一切正常。

#13


0  

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.

在我的例子中,问题是-我有app_folder和设置。py。然后我决定在app_folder中设置Settings文件夹——这与settings.y发生了冲突。刚刚重命名了设置文件夹——一切都工作了。