kb84tkhrのブログ

何を書こうか考え中です あ、あと組織とは関係ないってやつです 個人的なやつ

Djangoチュートリアル(7) 404

今日は404の返し方
raise Http404を使う
500用の例外とかもあるのかな

定義を見てみたら扱いが違う

class HttpResponseServerError(HttpResponse):
    status_code = 500

class Http404(Exception):
    pass

ほかにもいろんなステータスコードのHttpResponseが用意されてるけど
Exceptionなのは404だけっぽく見える
どういうことかな

データが存在しなければ404、っていうコードはこう

def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesnotExist:
        raise Http404("Question does not exist")
    return render(request, 'polls/detail.html', {'question': question})

あんまり関係ないけどこういうの書いててどこまでtryの中にいれるのがいいのか
ちょっとよくわからない
returnまで書いちゃったほうが見やすい気がするんだけど
できるだけtryの中は短くしたほうがいいんだって言われればそんな気もする

さてQuestionのレコードを消さないと404が出せない
adminサイトからやればいいわけだな
キーで紐付いたChoiceのレコードも消えた(当然

どれどれ

Page not found (404)
  Request Method:   GET
     Request URL:   http://127.0.0.1:8000/polls/1/
       Raised by:   polls.views.detail
Question does not exist

地味なの出た

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

って言ってるのでsettings.pyでDEBUG = Falseにしてみた
今度は

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

だって
ALLOWED_HOSTS = ['127.0.0.1']と設定して再トライ

Not Found
The requested URL /polls/1/ was not found on this server.

さらに地味になったか
テンプレートを使う方法が後で出てくる?

レコードがなければ404出す、だけならget_object_or_404()が使える

def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

Question does not existという引数がなくなってて
エラー画面に表示されるメッセージがNo Question matches the given query.になった
"Question"というのはクラス名だろうから英語の名詞にしておかないと
へんなメッセージになるな

設計思想
なぜ ObjectDoesNotExist 例外を高水準で自動的にキャッチせず、ヘルパー関数 get_object_or_404() を使うのでしょうか、また、なぜモデル API に ObjectDoesNotExist ではなく、 Http404 を送出させるのでしょうか?

うーん
なんか変だな
モデルAPIはHttp404じゃなくてObjectDoesNotExist送ってるよ

原文あたろう

Why do we use a helper function get_object_or_404() instead of automatically catching the ObjectDoesNotExist exceptions at a higher level, or having the model API raise Http404 instead of ObjectDoesNotExist?

ああ

なぜObjectDoesNotExist例外を高水準で自動的にキャッチしたり、モデルAPIにObjectDoesNotExistではなくHttp404 を送出させたりするのではなく、ヘルパー関数 get_object_or_404() を使うのでしょうか?

ってことか
まだ読みにくいけど

答えは、モデルレイヤとビューレイヤをカップリングしてしまうからです。

それはわかる