【问题标题】:Why does my custom 404 page return '404 ok' response in Django?为什么我的自定义 404 页面在 Django 中返回“404 ok”响应?
【发布时间】:2017-03-24 10:15:42
【问题描述】:

我必须使用 django 呈现自定义 404 模板。 我决定从它的基础开始:

def custom_page_not_found(request):
    response = render_to_response('404.html', {},
                              context_instance=RequestContext(request))
    response.status_code = 404
    return response

我很想知道为什么我找不到“404 not found”。如果我不使用 urls.py 中的 handler404,我将获得具有当前状态的空白 404 页面。 但不是当我想要一个自定义模板时。

有人知道为什么吗? (django 1.7.11)

【问题讨论】:

  • 如果您只想为您的 404 页面使用自定义模板,则无需设置 handler404 或创建自定义视图。只需将您的 404.html 模板粘贴到您的模板目录中即可。
  • 感谢您的评论。但是,如果我需要出于任何目的使用自定义视图,我不能有正确的404 not found http 响应吗?
  • 当然可以。但是您的问题很令人困惑;没有“404 ok”之类的东西,你的意思是它正在返回“200 ok”吗?

标签: python django


【解决方案1】:

在 Django 1.9+ 中,更改 status_code(例如更改为 404)将更改未设置的 reason_phrase(例如更改为“未找到”)。但是,您使用的是旧版本的 Django,因此您必须手动更改 reason_phrase,否则它将保持“正常”。

在创建响应时设置状态会更容易。

def custom_page_not_found(request):
    return render_to_response('404.html', {},
                              context_instance=RequestContext(request),
                              status=404)

由于render_to_response 快捷方式已过时,最好改用render

def custom_page_not_found(request):
    return render(request, '404.html', {}, status=404)

【讨论】:

  • 伙计,你是我一天中的阳光(伦敦天气)。我被困了这么久。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-02
  • 2010-09-25
  • 2017-09-23
  • 1970-01-01
  • 2014-07-29
  • 2018-12-26
相关资源
最近更新 更多