1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

DjangoのHttp404

Posted at

##この記事の内容
Djangoでよく見るHttp404を使った例外エラー処理について解説します。

views.py(よく見るエラー処理)
from django.http import Http404
from django.shortcuts import render
from polls.models import Poll

def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404("Poll does not exist")
    return render(request, 'polls/detail.html', {'poll': p})

##Http404は何がイケてるのか
そもそも、raiseは強制的に例外処理を出すためのpythonのメソッドです。
raise Http404では実際にページが存在するかどうかに関わらず、好きな時に404のエラーを出力することができます。
例えば以下のようなコードのときは、valueが2の時に404エラーを出し、それ以外の時には適切なルーティングを行うことができます。

views.py
def example(request,value):
    if value == 2;
        raise Http404
    return HttpResponseRedirect(reverse('example'))

実際にはこんな使い方はしないと思いますが、

views.py
def example(request,value):
    if request.method == "POST";
        raise Http404
    return HttpResponseRedirect(reverse('example'))

とすればPOSTの時だけ404エラーを出すこともできます。

##Http404を使ったエラーページのカスタマイズ

Http404を使ってエラーページをカスタマイズすることもできます。
自分の好きなhtmlファイルを作成し、templatesフォルダの直下に"404.html"を配置します。
そして、必ずsettings.pyの中でDEBUG=Falseにします。
(デフォルトではTrueになってます)

settings.py
DEBUG = False

もし、カスタマイズしなかった場合は、以下のようにデフォルトの404エラーページを返します。
Screenshot from 2020-12-07 17-13-57.png

また、DEBUG=Trueになっていた場合、通常の404debugページが表示されます。

##参考サイト
Djangoドキュメント
https://docs.djangoproject.com/en/3.1/topics/http/views/

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?