スクリプトのさまざまな場所でエラーメッセージを表示して 404 を発生させるのが好きHttp404("some error msg: %s" %msg)
です。
handler404 = Custom404.as_view()
私の意見でエラーをどのように処理すればよいか教えてください。私はDjangoにかなり慣れていないので、例が大いに役立ちます。
よろしくお願いします。
スクリプトのさまざまな場所でエラーメッセージを表示して 404 を発生させるのが好きHttp404("some error msg: %s" %msg)
です。
handler404 = Custom404.as_view()
私の意見でエラーをどのように処理すればよいか教えてください。私はDjangoにかなり慣れていないので、例が大いに役立ちます。
よろしくお願いします。
通常、404 エラーにカスタム メッセージはありませんが、実装したい場合は、django ミドルウェアを使用してこれを行うことができます。
ミドルウェア
from django.http import Http404, HttpResponse
class Custom404Middleware(object):
def process_exception(self, request, exception):
if isinstance(exception, Http404):
# implement your custom logic. You can send
# http response with any template or message
# here. unicode(exception) will give the custom
# error message that was passed.
msg = unicode(exception)
return HttpResponse(msg, status=404)
ミドルウェアの設定
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'college.middleware.Custom404Middleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
これでうまくいきます。私が間違ったことをしている場合は、私を修正してください。お役に立てれば。
一般に、404 エラーは「ページが見つかりません」エラーです。ページが見つからない場合にのみ発生する必要があるため、カスタマイズ可能なメッセージを含める必要はありません。
TemplateResponse
status パラメータを に設定して を返すことができます404
ビュー内でHttp404
例外を発生させます。通常、DoesNotExist
例外をキャッチすると実行されます。例えば:
from django.http import Http404
def article_view(request, slug):
try:
entry = Article.objects.get(slug=slug)
except Article.DoesNotExist:
raise Http404()
return render(request, 'news/article.html', {'article': entry, })
さらに良いことに、get_object_or_404
ショートカットを使用します。
from django.shortcuts import get_object_or_404
def article_view(request):
article = get_object_or_404(MyModel, pk=1)
return render(request, 'news/article.html', {'article': entry, })
404 Page not found
デフォルトの応答をカスタマイズしたい場合は、独自のテンプレート404.html
をtemplates
フォルダーに呼び出します。
多くのミドルウェアが変更された後、Django 2.2 (2019) の解決策を見つけました。これは、2013年のムハンマドの回答と非常によく似ています。つまり、次のとおりです。
ミドルウェア.py
from django.http import Http404, HttpResponse
class CustomHTTP404Middleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before the view (and later middleware) are called.
response = self.get_response(request)
# Code to be executed for each request/response after the view is called.
return response
def process_exception(self, request, exception):
if isinstance(exception, Http404):
message = f"""
{exception.args},
User: {request.user},
Referrer: {request.META.get('HTTP_REFERRER', 'no referrer')}
"""
exception.args = (message,)
また、これを最後に settings.py のミドルウェアに追加します。'app.middleware.http404.CustomHTTP404Middleware',
デフォルトの 404 ハンドラーは 404.html を呼び出します。派手なものが必要ない場合、または handler404 ビューを設定して 404 ハンドラーをオーバーライドできる場合は、それを編集できます --詳しくはこちらをご覧ください