LoginSignup
10
6

More than 3 years have passed since last update.

【Django】独自の403、404、500 エラーページを作成する

Posted at

概要

404 Not Foundなどのエラーページを作成する方法を調べたのでまとめます。

今回調べたエラー

以下のエラーコードについて触れていきます。

  • 403 Forbidden
  • 404 Not Found
  • 500 Internal Server Error

やり方

任意のtemplatesディレクトリの下に、

  • 403.html
  • 404.html
  • 500.html

を置きます。

すると、対象のエラーが吐かれるときに自動でテンプレートを読み取ってくれます。

myproject
  - myapp
    - urls.py
    - views.py
    - models.py
    - app.py
    - forms.py
    - templates
      - 403.html
      - 404.html
      - 500.html

以下のように、独自の404ページなどを実装します。

404.html
{% extends "base.html" %}
{% block content %}
<section>
    <div>
        <label>404 Not Found<br>お探しのページが見つかりませんでした。<br><a class="hover-under" href="{% url 'top' %}">トップページへ戻る</a></label>
    </div>
</section>
{% endblock %}

各エラーコードが吐き出される例外

これらのページは、それぞれのステータスコードが返されるべき例外を呼んであげると、返されます。

404 Not Found

django.httpパッケージの中にあるHttp404クラスをraiseします。

views.py
from django.http import Http404


class MyView(View):
    def index(self):
        raise Http404

403 Forbidden

django.core.exceptionsPermissionDeniedクラスがあります。

views.py
from django.core.exceptions import PermissionDenied


class MyView(View):
    def index(self):
        if not self.request.user.is_authenticated:
            raise PermissionDenied

500 Internal Server Error

構文エラーなど、通常のInternalServerErrorとなるものをキャッチしない、もしくは明示的に返した通常のエラーを使います。

views.py
from .models import Example


class MyView(View):
    def index(self):
        try:
            _instance = Example.objects.get(id=1)
        except Example.DoesNotExists:
            # 例外を投げる(普通はあまりやらない)
            raise Exception
10
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
6