View All Posts. MiCHiLU.com powered by Django ;-)

[Django]: 特定のviewで軽い404 Not Foundページを返す

templates/404.html テンプレートを使わないで 404 Not Found をレスポンスする方法。Ajaxなんかのリクエストに対して無駄に豪華な404ページを返してるんじゃないかと思われる時に。

from django.shortcuts import get_object_or_404
from django.views.generic.simple import direct_to_template
from django.views.defaults import page_not_found
from django.http import Http404

def api(request, param=None):
    try:
        if param is None:
            raise Http404
        item = get_object_or_404(Spam, pk=param)
    except Http404:
        #if settings.DEBUG: raise Http404
        return page_not_found(request, "404_lite.html")
    return direct_to_template(request, "api.html", dict(
        item = item,
    ))

404_lite.html ファイルの中身は空でもいいけど 404 とでも書いておいた方が人間に優しいと思います。 DEBUG=True の時も 404_lite.html が表示されますが お馴染みのdebug用404が見たい時は、コメントアウトのように settings.DEBUG を見てまたraiseしたりするのかな。

と、ここまで書いてドキュメントを見たらしっかり書いてあった。

django.views.defaults.page_not_found:
http://michilu.com/django/doc-ja/request_response/#the-404-page-not-found-view
HttpResponse のサブクラス:
http://michilu.com/django/doc-ja/request_response/#httpresponse-subclasses

書き直しバージョン。

from django.shortcuts import get_object_or_404
from django.views.generic.simple import direct_to_template
from django.http import HttpResponseNotFound, Http404

def api(request, param=None):
    try:
        if param is None:
            raise Http404
        item = get_object_or_404(Spam, pk=param)
    except Http404:
        return HttpResponseNotFound("404\n")
    return direct_to_template(request, "api.html", dict(
        item = item,
    ))

テンプレがいらなくなった。

Tue, 31 Jul 2007 22:48:05 +0900 source edit
Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 2.1 Japan License.
View All Posts. MiCHiLU.com powered by Django ;-)