LoginSignup
5
8

More than 5 years have passed since last update.

Django settings.py SECRET_KEYエラー

Posted at

settings.pyの中でdjangoモジュールをimportするとsettingsの置き換え時にSECRET_KEY設定がなくて怒られる話.

背景1

settings.pyの中で add_to_builtins('bootstrap3.templatetags.bootstrap3')
みたいに書いとけば templateの頭でいちいち{% load bootstrap3 %} を書く必要がなくなるらしい.
ということでさっそく記述.

from django.template.base import add_to_builtins

add_to_builtins('bootstrap3.templatetags.bootstrap3')

背景2

djangoはmanage.pyコマンド実行時に--settingsオプションを渡すことで使用する設定を変更できる.
これを利用して,test用の設定やdeploy用の設定を用意しておき,テスト環境や本番環境での起動時に
$ python manage.py runserver --settings=myproject.settings_production
のように実行する.

参考:gunicornの場合はこんな感じ
$ gunicorn -w 2 myproject.wsgi:application --settings=myproject.settings_production --bind=unix:///tmp/myproject.sock

本番環境用のsettingsはDEBUGフラグやDBが違うくらいなので,
下記のようにdefaultのsettingsをimportして必要な変数だけ上書き.

from .settings import *

DEBUG = False
ALLOWED_HOSTS = ['*']

DATABASES = {
    'default': {
        ...
    }
}

問題

背景1(settings.pyのなかでdjango.template.baseのimport)と背景2(settingsの置き換え)をすると
以下の様なエラーが吐かれて落ちる.
import django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.

原因

settingsの中でdjangoを呼び出し,その中でさらにsettingsを呼び出していたので,
無限ループ防止でデフォルトのsettingsのimportが抑制されていたらしい.

スクリーンショット 2015-07-15 12.31.37.png

対応策

settings.pyの中でadd_to_builtinsを実行するとまずいようなので myproject/__init__.pyに移動.
ただし,gunicornで実行する場合はmyproject/__init__.pyの中のdjango import時にDJANGO_SETTINGS_MODULE環境変数がないと怒られる場合がある(読み込むモジュール次第).

ImproperlyConfigured: Requested setting BOOTSTRAP3, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

# bootstrap3は中でsettingsを読み込むらしい.

というわけで,gunicornの起動も考慮した myproject/__init__.pyの中身はこんな感じになりました.

import os

from django.template.base import add_to_builtins


os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mailer.settings")

add_to_builtins('bootstrap3.templatetags.bootstrap3')
5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8