我在 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
网站/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
终端说:
[24/Mar/2018 22:32:17] "GET /test/ HTTP/1.1" 500 128
怎样才能故意得到404页面呢?
当您将 debug 设置为 False 时,您没有自定义处理程序,并且响应的状态代码为 404,将使用基本模板目录中的 404.html(如果存在)。要返回 404 状态的响应,您只需返回一个实例即可django.http.HttpResponseNotFound
。您收到 500 的原因是因为您提出了错误而不是返回响应。所以,你的测试函数可以简单地修改为这个
from django.http import HttpResponseNotFound
def test(request):
return HttpResponseNotFound("hello")
Update:
所以事实证明,您收到 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
不过,在这种情况下,您也可以只使用默认处理程序。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)