よしたく blog

ほぼ週刊で記事を書いています

Djangoの設定をHerokuの環境とローカルの環境で分ける方法

f:id:yoshitaku_jp:20180711100334p:plain

はじめに

Djangoで作ったWebアプリケーションをHerokuにアップロードしようとしたとき、Herokuの環境とローカルの環境で使っているDBが違ったので、設定を使い分けられたらいいなと思っていました。環境ごとに差異を出さず開発していくほうがいいと思いますが、今回はHerokuの環境とローカルの環境で設定をわける方法を知ったのでメモしておきます。

Herokuの環境へのデプロイ方法はこちら

yoshitaku-jp.hatenablog.com

local_setting.pyの作成

settings.pyがあるディレクトリにlocal_setting.pyを作成し、ローカルだけで使う設定を記述しておきます。HerokuではPostgreSQLが使われているので、settings.pyがいろいろ変更されているかと思います。ここではDjangoのプロジェクトを作った際のデフォルト設定をlocal_setting.pyに書いておきます。

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'SECRET_KEY'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'ownercard',

    'django.contrib.auth',
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.twitter',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'config.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'config.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'ja'

TIME_ZONE = 'Asia/Tokyo'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
AUTHENTICATION_BACKENDS = (
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',

    # `allauth` specific authentication methods, such as login by e-mail
    'allauth.account.auth_backends.AuthenticationBackend',
)

settings.pyの修正

末尾にlocal_setting.pyを読み込む設定を追加します。try exceptの形にし、ファイルがなくても処理が進むようにしておくのが通例のようです。これは他の分野にも応用できそうなので覚えておこう。

#settings.pyの末尾に追加
try:
    from local_settings import *
except ImportError:
    pass

.gitignoreにlocal_setting.pyの追加

config/local_setting.py.gitignoreに追加しておかないと、ローカルの設定がアップロードされてしまいます。

これで、Herokuの環境とローカルの環境で設定の使い分けができます。

ローカル環境でのサーバ実行コマンド

実際にローカルサーバを起動するためにpython manage.py runserverコマンドを実行し、サーバを起動させます。

明示的に起動させるには下記のようにするといいようです。

python manage.py runserver --settings config.local_settings