LoginSignup
7
6

More than 5 years have passed since last update.

DJangoメモ:はじめから(エラー画面設定編)

Last updated at Posted at 2013-12-16

まずは404とか500とか、エラー番号についての認識がぼんやりしていたので簡単にググりました。
http://human-dust.kdn.gr.jp/doujin/net/errormsg.html
http://www.seohacks.net/blog/crawl_index/http_statuscode/

404エラー

名前のまんまだが、Http404というモジュールを使う。
チュートリアルでの記述は以下。

from django.http import Http404
# ...
def detail(request, poll_id):
    try:  # ここのコードで・・・
        pobject = Poll.objects.get(pk=poll_id)  # pkって何だ?
    except Poll.DoesNotExist:  # こうなったら・・・・
        raise Http404  # 404エラーとして扱う
    return render_to_response('polls/detail.html', {'poll': pobject})  # 問題なければこっちに到達

また、こちらにも短縮形の書き方がある模様。その場合は、

from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    pobject = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': pobject})

という感じ。こちらはtry文を使わなくていいのか?
なお、前述のものも実はさりげなく前回出てきたshortcutsを使用している。
個人的には仕組みをちゃんと理解するまで省略形を使いたくないので、あえて以下のように直してみた。

from django.http import Http404
#…
def detail(request,poll_id):
    try:
        pobject = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    temp = loader.get_template('polls/detail.html')
    contxt = Context({
        'poll':pobject
    })
    return HttpResponse(temp.render(contxt))

ちょっと長いけどやっぱりこちらのほうが流れをつかめる感じがする。

まあそれはいいとして、肝心のエラー画面のほうはわざわざ自分でテンプレートを作らなくてもDJangoが用意してくれたものがあるみたい。自分は今のところ特に自作する必要性を感じないのでスルーする。
もし作りたいのなら404.htmlというファイル名でテンプレートディレクトリに置けばいいらしい。 ただし、設定の仕方は説明を読んでもよく分からなかった(URLConf内にhandler404という変数を定義?)。

確認の方法:
  • setting.pyのDEBUGをFalseに(Trueだとトレースバックが優先される)

  • 同じくALLOWED_HOSTSを設定(’.example.com’みたいに自分のドメインを入れるらしいが、何でもいいなら’*’でOK)

なお、500(サーバーエラー)の場合でもやることはさほど変わらない模様。

次はURLConfの単純化と分割をやります。

7
6
1

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
7
6