如何在django中有意返回404页面

tou*_*ist 13 django

我在django中制作了自定义404页面.而且我试图故意获得404错误页面.

MyProject的/ urls.py:

from website.views import customhandler404, customhandler500, test

urlpatterns = [
    re_path(r'^admin/', admin.site.urls),
    re_path(r'^test/$', test, name='test'),
]
handler404 = customhandler404
handler500 = customhandler500
Run Code Online (Sandbox Code Playgroud)

网站/ views.py

def customhandler404(request):
    response = render(request, '404.html',)
    response.status_code = 404
    return response


def customhandler500(request):
    response = render(request, '500.html',)
    response.status_code = 500
    return response

def test(request):
    raise Http404('hello')
Run Code Online (Sandbox Code Playgroud)

但是当我去127.0.0.1:8000/test/时,似乎又回来了 500.html

终端说:

[24/Mar/2018 22:32:17] "GET /test/ HTTP/1.1" 500 128

我怎么能故意得到404页面?

pkq*_*xdd 19

将debug设置为False时,您没有自定义处理程序,并且响应的状态代码为404,使用基本模板目录中的404.html(如果存在).要返回404状态的响应,您只需返回一个实例即可django.http.HttpResponseNotFound.你得到500的原因是因为你引发了错误而不是返回响应.因此,您的测试功能可以简单地修改为此

from django.http import HttpResponseNotFound
def test(request):
    return HttpResponseNotFound("hello")         
Run Code Online (Sandbox Code Playgroud)

更新:

所以事实证明,你得到500错误的原因并不是你提出异常,而是有不正确的功能签名.当我在半年多前回答这个问题时,我忘记了django为你捕获了HTTP404异常.但是,处理程序视图具有与普通视图不同的签名.404的默认处理程序是defaults.page_not_found(request, exception, template_name='404.html')3个参数.所以你的自定义处理程序应该是

def customhandler404(request, exception, template_name='404.html'):
    response = render(request, template_name)
    response.status_code = 404
    return response
Run Code Online (Sandbox Code Playgroud)

虽然,在这种情况下,您也可以使用默认处理程序.

  • 关于 `HttpResponseNotFound` 通常最好提高 [`Http404`](/sf/answers/539739581/) [例外](https://docs.djangoproject.com/en/2.2/topics/http /views/#the-http404-exception)。这样你只需要定义一次模板(除非被覆盖,否则`404.html`)。 (3认同)