Skip to content

Django環境構築完全ガイド

Djangoプロジェクトの環境構築から、実務で使えるベストプラクティスまで詳しく解説します。

1. Pythonのインストールとバージョン確認

Section titled “1. Pythonのインストールとバージョン確認”

Djangoは、Python 3.8以上をサポートしています。最新の安定版を使用することを推奨します。

Terminal window
# Pythonのバージョン確認
python --version
# または
python3 --version
# 推奨: Python 3.11以上

pyenvを使用したPythonバージョン管理(推奨)

Section titled “pyenvを使用したPythonバージョン管理(推奨)”
Terminal window
# 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.5

仮想環境は、プロジェクトごとに独立したPython環境を作成する仕組みです。これにより、異なるプロジェクトで異なるパッケージバージョンを使用できます。

Terminal window
# プロジェクトディレクトリの作成
mkdir myproject
cd myproject
# 仮想環境の作成
python -m venv venv
Terminal window
# macOS / Linux
source venv/bin/activate
# Windows (コマンドプロンプト)
venv\Scripts\activate
# Windows (PowerShell)
venv\Scripts\Activate.ps1
Terminal window
deactivate
Terminal window
# 最新版のインストール
pip install django
# 特定バージョンのインストール
pip install django==4.2.7
Terminal window
# requirements.txtの作成
pip freeze > requirements.txt
# 他の環境でのインストール
pip install -r requirements.txt
requirements.txt
Django==4.2.7
djangorestframework==3.14.0
psycopg2-binary==2.9.9
python-decouple==3.8
django-cors-headers==4.3.0
requirements/base.txt
Django==4.2.7
djangorestframework==3.14.0
psycopg2-binary==2.9.9
# requirements/dev.txt
-r base.txt
django-debug-toolbar==4.2.0
pytest-django==4.7.0
black==23.11.0
flake8==6.1.0
# requirements/prod.txt
-r base.txt
gunicorn==21.2.0
whitenoise==6.6.0
Terminal window
# 現在のディレクトリにプロジェクトを作成
django-admin startproject myproject .
# プロジェクト名のディレクトリを作成
django-admin startproject myproject
myproject/
├── manage.py
├── myproject/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── wsgi.py
│ └── asgi.py
└── venv/
Terminal window
# アプリケーションの作成
python manage.py startapp myapp
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp', # 作成したアプリケーションを追加
]
settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
Terminal window
# PostgreSQLのインストール
# macOS
brew install postgresql
# Ubuntu
sudo apt-get install postgresql postgresql-contrib
# psycopg2のインストール
pip install psycopg2-binary
settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydb',
'USER': 'myuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '5432',
}
}
Terminal window
# .envファイルの作成
pip install python-decouple
settings.py
from 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'),
}
}
.env
DB_NAME=mydb
DB_USER=myuser
DB_PASSWORD=mypassword
DB_HOST=localhost
DB_PORT=5432
Terminal window
# マイグレーションファイルの作成
python manage.py makemigrations
# マイグレーションの適用
python manage.py migrate
# マイグレーションの状態確認
python manage.py showmigrations
Terminal window
# スーパーユーザーの作成
python manage.py createsuperuser
# 対話形式で以下を入力:
# Username: admin
# Email address: admin@example.com
# Password: ********
# Password (again): ********
Terminal window
# デフォルトポート(8000)で起動
python manage.py runserver
# カスタムポートで起動
python manage.py runserver 8080
# すべてのIPアドレスからアクセス可能にする
python manage.py runserver 0.0.0.0:8000

9. 実務でのベストプラクティス

Section titled “9. 実務でのベストプラクティス”
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/
settings/base.py
import os
from pathlib import Path
from 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 = True
USE_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'
settings/development.py
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']
settings/production.py
from .base import *
DEBUG = False
ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=lambda v: [s.strip() for s in v.split(',')])
# セキュリティ設定
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
# 静的ファイルの配信(WhiteNoise)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
.gitignore
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
venv/
env/
ENV/
# Django
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
/media
/staticfiles
# 環境変数
.env
.env.local
# IDE
.vscode/
.idea/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db

問題1: 仮想環境が認識されない

Section titled “問題1: 仮想環境が認識されない”

原因:

  • 仮想環境が有効化されていない
  • パスが正しく設定されていない

解決策:

Terminal window
# 仮想環境の再作成
rm -rf venv
python -m venv venv
source venv/bin/activate # macOS/Linux
# または
venv\Scripts\activate # Windows

問題2: マイグレーションエラー

Section titled “問題2: マイグレーションエラー”

原因:

  • データベースが正しく設定されていない
  • マイグレーションファイルに問題がある

解決策:

Terminal window
# マイグレーションの状態確認
python manage.py showmigrations
# 特定のアプリのマイグレーションをリセット(開発環境のみ)
python manage.py migrate myapp zero
python manage.py makemigrations myapp
python manage.py migrate myapp

これで、Djangoの環境構築の基礎知識と実務での使い方を理解できるようになりました。