Djangoで403ページなどを自前のテンプレートに変更する方法をご紹介します。
条件
- Django 2.1.4
- Python 3.7.0
デフォルトのエラーページ
ここは、以下のエラーページについて対応します。
| 403 | Forbidden | アクセス権限がありません |
| 404 | Not Found | 該当のページが見つかりません |
| 500 | Internal Server Error | サーバー内部エラー |
403エラー(Forbidden)
404エラー(Page Not Found)
500エラー(Page Not Found)
自前のエラーページ
自前のエラーページにするには、それぞれ以下のようにtemplatesフォルダにhtmlファイルをします。
myApp └templates ├ 403.html ├ 404.html └ 500.html
403エラー(Forbidden)
プロジェクト直下のtemplatesフォルダの下に「403.html」を追加します。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<section>
<div class="error403">
<h1>403 Forbidden</h1>
</div>
<p>アクセス権限がありません。</p>
{% if exception %}
<p style="color: red">{{ exception }}</p>
{% endif %}
</section>
<section>
<p><a href="javascript:history.back()">< Back</a></p>
</section>
</body>
</html>
404エラー(Page Not Found)
プロジェクト直下のtemplatesフォルダの下に「404.html」を追加します。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<section>
<div class="error404">
<h1>404 Page Not Found</h1>
<p>リクエストされたURL {{ request.get_full_path }} は見つかりませんでした。</p>
</div>
</section>
<section>
<p><a href="javascript:history.back()">< Back</a></p>
</section>
</body>
</html>
500エラー(Internal Server Error)
プロジェクト直下のtemplatesフォルダの下に「500.html」を追加します。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<section>
<div class="error500">
<h1>500 Internal Server Error</h1>
</div>
<p>サーバー内部エラーです。</p>
{% if exception %}
<p style="color: red">{{ exception }}</p>
{% endif %}
</section>
<section>
<p><a href="javascript:history.back()">< Back</a></p>
</section>
</body>
</html>
自前の404、500エラー確認
自前の404、500エラーを開発環境で確認する場合、以下の設定が必要です。
settings.py
# settings.py DEBUG = False # Trueにするとデバッグ情報が入った404エラー画面が表示されます。 ALLOWED_HOSTS = ['127.0.0.1'] # DEBUG = Falseにした場合、適切なホスト情報を設定する必要があります。
404エラーを発生させる方法
存在しないURLにアクセスします。
500エラーを発生させる方法
以下ソースを追記し指定のURLにアクセスします。
(http://127.0.0.1:8000/test/)
# urls.py抜粋
urlpatterns = [
・・・
# 500エラー確認用
path('test/', views.my_test_500_view, name='test'),
]
# views.py抜粋
from django.http import HttpResponseServerError
def my_test_500_view(request):
# Return an "Internal Server Error" 500 response code.
return HttpResponseServerError
動作結果
403エラー(Forbidden)
404エラー(Page Not Found)
500エラー(Page Not Found)
参考
Django公式:Error views
https://docs.djangoproject.com/ja/2.1/ref/views/#error-views
stackoverflow:How can I trigger a 500 error in Django?
https://stackoverflow.com/questions/24660406/how-can-i-trigger-a-500-error-in-django

