13

スクリプトのさまざまな場所でエラーメッセージを表示して 404 を発生させるのが好きHttp404("some error msg: %s" %msg) です。

handler404 = Custom404.as_view()

私の意見でエラーをどのように処理すればよいか教えてください。私はDjangoにかなり慣れていないので、例が大いに役立ちます。
よろしくお願いします。

4

9 に答える 9

10

通常、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',
)

これでうまくいきます。私が間違ったことをしている場合は、私を修正してください。お役に立てれば。

于 2013-05-12T08:53:28.110 に答える
9

一般に、404 エラーは「ページが見つかりません」エラーです。ページが見つからない場合にのみ発生する必要があるため、カスタマイズ可能なメッセージを含める必要はありません。

TemplateResponsestatus パラメータを に設定して を返すことができます404

于 2013-05-07T09:03:22.567 に答える
6

ビュー内で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.htmltemplatesフォルダーに呼び出します。

于 2017-02-13T01:20:44.873 に答える
3

多くのミドルウェアが変更された後、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',

于 2019-04-24T21:18:54.227 に答える
0

デフォルトの 404 ハンドラーは 404.html を呼び出します。派手なものが必要ない場合、または handler404 ビューを設定して 404 ハンドラーをオーバーライドできる場合は、それを編集できます --詳しくはこちらをご覧ください

于 2013-05-07T09:06:21.717 に答える