Django用一条消息筹集404

DGT*_*DGT 7 django django-forms django-views

我喜欢在脚本中的不同位置提出404错误信息,例如:Http404("some error msg: %s" %msg) 所以,在我的urls.py中,我包括:

handler404 = Custom404.as_view()
Run Code Online (Sandbox Code Playgroud)

任何人都可以告诉我如何处理我的观点中的错误.我对Django很新,所以一个例子会有很多帮助.
提前谢谢了.

Muh*_*K K 9

一般情况下,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)
Run Code Online (Sandbox Code Playgroud)

中间件设置

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',
)
Run Code Online (Sandbox Code Playgroud)

这样就可以了.如果我做错任何事,请纠正我.希望这可以帮助.


ahe*_*rok 8

通常,404错误是"找不到页面"错误 - 它不应该具有可自定义的消息,仅仅因为它应该仅在找不到页面时引发.

您可以返回TemplateResponse状态参数设置为404


Muh*_*eed 6

是的,我们可以在引发 Http404 时显示特定的异常消息。

像这样传递一些异常消息

raise Http404('Any kind of message ')
Run Code Online (Sandbox Code Playgroud)

将 404.html 页面添加到 templates 目录中。

模板/404.html

{{exception}}
Run Code Online (Sandbox Code Playgroud)


Max*_*ysh 5

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, })
Run Code Online (Sandbox Code Playgroud)

更好的是,使用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, })
Run Code Online (Sandbox Code Playgroud)

如果您想自定义默认404 Page not found响应,把你叫自己的模板404.htmltemplates文件夹。