如何在Django中有意地返回404页面 [英] How to return 404 page intentionally in django

查看:680
本文介绍了如何在Django中有意地返回404页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django中创建了自定义404页面。而且我正试图故意获取404错误页面。

I made custom 404 page in django. And I'm trying to get 404 error page intentionally.

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

website / 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')

但是当我执行127.0.0.1:8000/test/时,似乎返回 500.html

But when I go 127.0.0.1:8000/test/ , It seems to return 500.html

和终端s ays:

[24 / Mar / 2018 22:32:17] GET / test / HTTP / 1.1 500128

我如何有意获取404页面?

How can I intentionally get 404 page?

推荐答案

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

When you set debug to False, you don't have a custom handler, and the status code of the response is 404, the 404.html (if present) in your base template directory is used. To return a response with a 404 status, you can simply return an instance of django.http.HttpResponseNotFound. The reason you got a 500 is because you raised an error instead of returning a response. So, your test function can be simply modified to this

from django.http import HttpResponseNotFound
def test(request):
    return HttpResponseNotFound("hello")         

更新:

因此,事实证明您收到500错误的原因不是您引发了异常,而是函数签名不正确。当我半年多前回答这个问题时,我忘记了django为您捕获了HTTP404异常。但是,处理程序视图具有与普通视图不同的签名。 404的默认处理程序为 defaults.page_not_found(请求,异常,template_name = 404.html),其中包含3个参数。因此,您的自定义处理程序实际上应该是

So it turned out that the reason you are getting a 500 error was not that you raised an exception, but having incorrect function signatures. When I answered this question more than half a year ago I forgot that django catches HTTP404 exception for you. However, the handler view has different signatures than the normal views. The default handler for 404 is defaults.page_not_found(request, exception, template_name='404.html'), which takes 3 arguments. So your custom handler should actually be

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

尽管在这种情况下,您也可以只使用默认处理程序。

Although, in this case, you may as well just use the default handler.

这篇关于如何在Django中有意地返回404页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆