エラーページのカスタマイズ - Django

ディレクトリ構成

  • pythonApp
    • env
      • django_app
        • django_app
          • ...
        • hello
          • migrations
            • ...
            • templates
              • hello
                • index.html
              • 404.html
          • __init__.py
          • admin.py
          • apps.py
          • models.py
          • tests.py
          • views.py
        • db.sqlite3
        • manage.py
      • ...

エラーページの作成

「 settings.py 」を次のように編集します。

「 DEBUG = True 」のままでは、Django のデバッグ専用のページが表示されます。

pythonApp\auth\auth\auth\settings.py

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

ALLOWED_HOSTS = ["127.0.0.1", "localhost"]

表示したいエラーページを作成するには、「 エラー番号.html 」のファイル名を作成します。

pythonApp\auth\auth\hello\templates\404.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>404</title>
</head>
<body>
  <h1>Not Found 404</h1>
  <p><a href="/hello">トップページに戻る</a></p>
</body>
</html>

ブラウザから存在しないアドレスにアクセスし、エラー画面が表示されるか確認します。