Django環境構築完全ガイド
Django環境構築完全ガイド
Section titled “Django環境構築完全ガイド”Djangoプロジェクトの環境構築から、実務で使えるベストプラクティスまで詳しく解説します。
1. Pythonのインストールとバージョン確認
Section titled “1. Pythonのインストールとバージョン確認”Pythonのバージョン要件
Section titled “Pythonのバージョン要件”Djangoは、Python 3.8以上をサポートしています。最新の安定版を使用することを推奨します。
# Pythonのバージョン確認python --version# またはpython3 --version
# 推奨: Python 3.11以上pyenvを使用したPythonバージョン管理(推奨)
Section titled “pyenvを使用したPythonバージョン管理(推奨)”# pyenvのインストール(macOS)brew install pyenv
# pyenvのインストール(Linux)curl https://pyenv.run | bash
# Python 3.11のインストールpyenv install 3.11.5
# プロジェクトディレクトリでPythonバージョンを設定pyenv local 3.11.52. 仮想環境の作成と有効化
Section titled “2. 仮想環境の作成と有効化”仮想環境とは
Section titled “仮想環境とは”仮想環境は、プロジェクトごとに独立したPython環境を作成する仕組みです。これにより、異なるプロジェクトで異なるパッケージバージョンを使用できます。
仮想環境の作成
Section titled “仮想環境の作成”# プロジェクトディレクトリの作成mkdir myprojectcd myproject
# 仮想環境の作成python -m venv venv仮想環境の有効化
Section titled “仮想環境の有効化”# macOS / Linuxsource venv/bin/activate
# Windows (コマンドプロンプト)venv\Scripts\activate
# Windows (PowerShell)venv\Scripts\Activate.ps1仮想環境の無効化
Section titled “仮想環境の無効化”deactivate3. Djangoのインストール
Section titled “3. Djangoのインストール”基本的なインストール
Section titled “基本的なインストール”# 最新版のインストールpip install django
# 特定バージョンのインストールpip install django==4.2.7requirements.txtの作成
Section titled “requirements.txtの作成”# requirements.txtの作成pip freeze > requirements.txt
# 他の環境でのインストールpip install -r requirements.txt実務でのベストプラクティス
Section titled “実務でのベストプラクティス”Django==4.2.7djangorestframework==3.14.0psycopg2-binary==2.9.9python-decouple==3.8django-cors-headers==4.3.0開発環境と本番環境の分離
Section titled “開発環境と本番環境の分離”Django==4.2.7djangorestframework==3.14.0psycopg2-binary==2.9.9
# requirements/dev.txt-r base.txtdjango-debug-toolbar==4.2.0pytest-django==4.7.0black==23.11.0flake8==6.1.0
# requirements/prod.txt-r base.txtgunicorn==21.2.0whitenoise==6.6.04. Djangoプロジェクトの作成
Section titled “4. Djangoプロジェクトの作成”プロジェクトの作成
Section titled “プロジェクトの作成”# 現在のディレクトリにプロジェクトを作成django-admin startproject myproject .
# プロジェクト名のディレクトリを作成django-admin startproject myprojectプロジェクト構造
Section titled “プロジェクト構造”myproject/├── manage.py├── myproject/│ ├── __init__.py│ ├── settings.py│ ├── urls.py│ ├── wsgi.py│ └── asgi.py└── venv/アプリケーションの作成
Section titled “アプリケーションの作成”# アプリケーションの作成python manage.py startapp myappアプリケーションの登録
Section titled “アプリケーションの登録”INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', # 作成したアプリケーションを追加]5. データベースの設定
Section titled “5. データベースの設定”SQLite(開発環境)
Section titled “SQLite(開発環境)”DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }}PostgreSQL(本番環境)
Section titled “PostgreSQL(本番環境)”# PostgreSQLのインストール# macOSbrew install postgresql
# Ubuntusudo apt-get install postgresql postgresql-contrib
# psycopg2のインストールpip install psycopg2-binaryDATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydb', 'USER': 'myuser', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '5432', }}環境変数の使用(推奨)
Section titled “環境変数の使用(推奨)”# .envファイルの作成pip install python-decouplefrom decouple import config
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': config('DB_HOST', default='localhost'), 'PORT': config('DB_PORT', default='5432'), }}DB_NAME=mydbDB_USER=myuserDB_PASSWORD=mypasswordDB_HOST=localhostDB_PORT=54326. マイグレーションの実行
Section titled “6. マイグレーションの実行”# マイグレーションファイルの作成python manage.py makemigrations
# マイグレーションの適用python manage.py migrate
# マイグレーションの状態確認python manage.py showmigrations7. スーパーユーザーの作成
Section titled “7. スーパーユーザーの作成”# スーパーユーザーの作成python manage.py createsuperuser
# 対話形式で以下を入力:# Username: admin# Email address: admin@example.com# Password: ********# Password (again): ********8. 開発用サーバーの起動
Section titled “8. 開発用サーバーの起動”# デフォルトポート(8000)で起動python manage.py runserver
# カスタムポートで起動python manage.py runserver 8080
# すべてのIPアドレスからアクセス可能にするpython manage.py runserver 0.0.0.0:80009. 実務でのベストプラクティス
Section titled “9. 実務でのベストプラクティス”プロジェクト構造(推奨)
Section titled “プロジェクト構造(推奨)”myproject/├── manage.py├── requirements/│ ├── base.txt│ ├── dev.txt│ └── prod.txt├── .env├── .gitignore├── myproject/│ ├── __init__.py│ ├── settings/│ │ ├── __init__.py│ │ ├── base.py│ │ ├── development.py│ │ └── production.py│ ├── urls.py│ ├── wsgi.py│ └── asgi.py├── apps/│ ├── accounts/│ ├── blog/│ └── api/└── static/└── media/設定ファイルの分割
Section titled “設定ファイルの分割”import osfrom pathlib import Pathfrom decouple import config
BASE_DIR = Path(__file__).resolve().parent.parent.parent
SECRET_KEY = config('SECRET_KEY')DEBUG = config('DEBUG', default=False, cast=bool)
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',]
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 = 'myproject.urls'
WSGI_APPLICATION = 'myproject.wsgi.application'
# データベース設定DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': config('DB_HOST', default='localhost'), 'PORT': config('DB_PORT', default='5432'), }}
# 国際化設定LANGUAGE_CODE = 'ja'TIME_ZONE = 'Asia/Tokyo'USE_I18N = TrueUSE_TZ = True
# 静的ファイル設定STATIC_URL = '/static/'STATIC_ROOT = BASE_DIR / 'staticfiles'
MEDIA_URL = '/media/'MEDIA_ROOT = BASE_DIR / 'media'
# デフォルトの主キーフィールドDEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'from .base import *
DEBUG = True
INSTALLED_APPS += [ 'debug_toolbar',]
MIDDLEWARE += [ 'debug_toolbar.middleware.DebugToolbarMiddleware',]
# 開発環境用のデータベース設定DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }}
# デバッグツールバーの設定INTERNAL_IPS = ['127.0.0.1']from .base import *
DEBUG = False
ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=lambda v: [s.strip() for s in v.split(',')])
# セキュリティ設定SECURE_SSL_REDIRECT = TrueSESSION_COOKIE_SECURE = TrueCSRF_COOKIE_SECURE = TrueSECURE_BROWSER_XSS_FILTER = TrueSECURE_CONTENT_TYPE_NOSNIFF = True
# 静的ファイルの配信(WhiteNoise)STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'.gitignoreの設定
Section titled “.gitignoreの設定”# Python__pycache__/*.py[cod]*$py.class*.so.Pythonvenv/env/ENV/
# Django*.loglocal_settings.pydb.sqlite3db.sqlite3-journal/media/staticfiles
# 環境変数.env.env.local
# IDE.vscode/.idea/*.swp*.swo
# OS.DS_StoreThumbs.db10. よくある問題と解決策
Section titled “10. よくある問題と解決策”問題1: 仮想環境が認識されない
Section titled “問題1: 仮想環境が認識されない”原因:
- 仮想環境が有効化されていない
- パスが正しく設定されていない
解決策:
# 仮想環境の再作成rm -rf venvpython -m venv venvsource venv/bin/activate # macOS/Linux# またはvenv\Scripts\activate # Windows問題2: マイグレーションエラー
Section titled “問題2: マイグレーションエラー”原因:
- データベースが正しく設定されていない
- マイグレーションファイルに問題がある
解決策:
# マイグレーションの状態確認python manage.py showmigrations
# 特定のアプリのマイグレーションをリセット(開発環境のみ)python manage.py migrate myapp zeropython manage.py makemigrations myapppython manage.py migrate myappこれで、Djangoの環境構築の基礎知識と実務での使い方を理解できるようになりました。