LoginSignup
2

More than 3 years have passed since last update.

posted at

updated at

Organization

Djangoのデフォルトエラーページが DEBUG=Falseだと見れないのはなんでか調べた

はじめに

この調査記事は Django2.1.4 を 2019/01/04 時点で調べてみたときのメモです。

流れ

$ django-admin startproject mysite
$ python mysite/manage.py runserver

した際に、 http://127.0.0.1:8000/ を見ると出てくるこのページ

image.png

が、 mysite/settings.pyDEBUG = True ではなく、 DEBUG = False にしたら表示されなくなったということで、調べてみた。

まずは

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False.

が出るので、とりあえず

settings.py
ALLOWED_HOSTS = ['127.0.0.1']

を追加しておく。

すると

image.png

となってしまう。

ではこのスタートページは一体?

このファイルがテンプレートして呼び出されているようだ。

どうやら debug.py が呼ばれている様子。

debug.py
# technical_404_response
     else:

         if (not tried or (                  # empty URLconf 
             request.path == '/' and
             len(tried) == 1 and             # default URLconf
             len(tried[0]) == 1 and
             getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin'
         )):
             return default_urlconf(request)

ということなので、要するに特定の条件の404(要はhttps://127.0.0.1:8000/ のような呼び出し)であればこのページを出している、ということだった。

確かにこれ以外の404は DEBUG = True であれば

image.png

こんな感じになる。

もう少し追ってみると

exception.py
def response_for_exception(request, exc):
    if isinstance(exc, Http404):
        if settings.DEBUG:
            response = debug.technical_404_response(request, exc)
        else:
            response = get_exception_response(request, get_resolver(get_urlconf()), 404, exc)

確かに DEBUG = True のときだけこのページが利用されていることがわかりました!

mysite/urls.py
 urlpatterns = [
      path('', ここになにか),
      path('admin/', admin.site.urls),
 ]

って書くことでうまいことやるか、テンプレートをおいたりビューを定義すれば良さそうですね。

because DEBUG=True is in your settings file and you have not configured any URLs

って書いてあるとおりだったというわけか。なるほど。

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
What you can do with signing up
2