为什么我的自定义404页面返回' 404 ok' Django的回应?

时间:2016-11-10 11:37:34

标签: python django

我用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;未找到404"。如果我不使用urls.py中的handler404,我将获得具有当前状态的空白404页面。 但是,当我想要一个自定义模板时,不是这样。

有谁知道为什么? (django 1.7.11)

1 个答案:

答案 0 :(得分:2)

在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)
相关问题