2.デプロイ前にすべきこと
.gitignoreの作成
このファイルをルートディレクトリ直下につくります
このファイルに書かれた中身はコミットされなくなります
db.sqlite3
.vscode
__pycache__
*.pyc
.DS_Store
.env
requirements.txtの作成
Requirementsとは必需品という意味です
アプリを動かすために必要な必要なパッケージをリスト化します
サーバー側(Render)には外部ライブラリがインストールされていないので、このファイルを見てインストールします
type nul > requirements.txt
pip freeze > requirements.txt
ただしこれだとアプリで使っているライブラリだけでなく、これまでインストールしたライブラリが全部インストールされるので、デプロイ時にエラーが発生しやすくなります。Views.pyでImportしているライブラリだけ手動で書き込みます
django==5.0.4
dj-database-url
dj-static
python-decouple
django-environ
gunicorn
psycopg2-binary
whitenoise
django-cleanup
yt-dlp
whitenoise(settings.py)
RenderはWhitenoiseというミドルウェアで静的ファイルを表示しています
pip install whitenoise
pip install gunicorn
settings.pyでミドルウェアを設定します
MIDDLEWARE = [
"whitenoise.middleware.WhiteNoiseMiddleware", <--- 追加
]
STATIC_URL = "static/"
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
アクセスを許可するホストの設定(settings.py)
RenderダッシュボードでDJANGO_ALLOWED_HOSTSを設定します
ALLOWED_HOSTS = os.getenv('DJANGO_ALLOWED_HOSTS', 'your-app.onrender.com').split(',')
※ローカルならALLOWED_HOSTS = ['*']でOKです
データベースの変更(settings.py)
RenderではSQLite3ではなくPostgreSQLを使います
from dj_database_url import parse as dburl
from decouple import config
default_dburl = "sqlite:///" + str(BASE_DIR / "db.sqlite3")
DATABASES = {
"default": config("DATABASE_URL", default=default_dburl, cast=dburl),
}
デバックの変更
誰でもデバッグできるとセキュリティ上よろしくないのでFalseに変えます
DEBUG = os.getenv('DJANGO_DEBUG', 'False') = 'True'
スーパーユーザーの作成(settings.py)(.env)
SUPERUSER_NAME = config("SUPERUSER_NAME")
SUPERUSER_EMAIL = config("SUPERUSER_EMAIL")
SUPERUSER_PASSWORD = config("SUPERUSER_PASSWORD")
.envファイルをルートディレクトリ直下に新規作成
SUPERUSER_NAME=admin
SUPERUSER_EMAIL=admin@admin.com
SUPERUSER_PASSWORD=password
app/management/commands/superuser.py
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.conf import settings
User = get_user_model()
class Command(BaseCommand):
def handle(self, *args, **options):
if not User.objects.filter(username=settings.SUPERUSER_NAME).exists():
User.objects.create_superuser(
username=settings.SUPERUSER_NAME,
email=settings.SUPERUSER_EMAIL,
password=settings.SUPERUSER_PASSWORD
)
print("スーパーユーザー作成")
build.sh(おそらくビルド時に実行するコマンドをまとめたもの)
ルートディレクトリ直下に配置します
#!/usr/bin/env bash
# exit on error
set -o errexit
pip install -r requirements.txt
python manage.py collectstatic --no-input
python manage.py migrate
python manage.py superuser
render.yaml
databases:
- name: django_render_db
region: singapore
plan: free
databaseName: django_render_db
user: django_user
services:
- type: web
name: django_render
env: python
region: singapore
buildCommand: './build.sh'
startCommand: 'gunicorn mysite.wsgi:application'
plan: free
branch: main
healthCheckPath: /
envVars:
- key: DATABASE_URL
fromDatabase:
name: django_render_db
property: connectionString
- key: SECRET_KEY
generateValue: true
- key: WEB_CONCURRENCY
value: 4
autoDeploy: true
startCommand: ‘gunicorn mysite.wsgi:application’ はウェブサーバーを起動したときにmysiteディレクトリのwsgi,pyを実行してくださいという意味です
wsgi.pyがdjangoprojectというディレクトリ直下にあれば、mysite -> djangoproject に書き換える必要があります
書き換えないでデプロイすると「ModuleNotFoundError: No module named ‘mysite’」というエラーがRenderで発生します
BACK