【问题标题】:How to return 404 page intentionally in django如何在 django 中故意返回 404 页面
【发布时间】:2018-09-03 01:15:41
【问题描述】:

我在 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 页面?

【问题讨论】:

  • 如果您查看日志/管理员电子邮件或启用调试,回溯应该会告诉您 500 错误的原因。也许你忘记了导入from django.http import Http404。请注意,默认的 404 和 500 处理程序已经分别呈现 404.html500.html 模板,因此您可以删除自定义处理程序。不建议对 500 页面使用 render,因为在尝试渲染 500.html 模板时可能会重复该错误。
  • 我刚刚编辑了我的答案,希望它对你仍然有用。

标签: django


【解决方案1】:

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

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

更新:

事实证明,您收到 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

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

【讨论】:

  • 关于HttpResponseNotFound,通常最好提高Http404 exception。这样您只需定义一次模板(404.html 除非被覆盖)。
猜你喜欢
  • 1970-01-01
  • 2013-08-28
  • 2020-05-12
  • 2020-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多