Django自定义处理程序404显示404但给出标题200 [英] Django custom handler404 shows 404 but gives header 200

查看:230
本文介绍了Django自定义处理程序404显示404但给出标题200的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为认证的Django网站制作了一个自定义处理程序404,以避免信息泄露。

I made a custom handler404 for a authenticated Django website to avoid information leakage.

def check_logged_in_404(request):
    """ Custom 404. Show friendly 404 when logged in and redirect to /login
    when not logged in.
    """
    if request.user.is_authenticated():
        return render_to_response('404.html')
    else:
        return HttpResponseRedirect('/login')

功能上它完全符合我的要求。然而,404返回页面的状态为200,这是正确的代码。但是这显然需要是404的返回状态。

Functionally it does exactly what I want. However the 404 return page has a status 200, which is correct code-wise. But this obviously needs to be a 404 return status.

raise404不起作用,因为如果不是以无限递归结尾,那么它返回到这里,从而导致相同的问题。

A raise404 doesn't work because, if not ending in a infinite recursion, it comes back here and thus results in the same issue.

我尝试了一个HttpResponseNotFound,但这只需要一个字符串作为参数,而不是一个模板,而不是DRY-ish。

I tried a HttpResponseNotFound, but this only takes a string as a argument and not a template, which is not to DRY-ish.

我手动尝试设置标题:

    response = render_to_response('404.html')
    response['Status'] = "Not Found - 404"
    return response

然后状态标题确实设置,但浏览器仍然显示200。

Then the status header is indeed set but the browser still shows up a 200.

我没有选择..任何人有提示,请成为我的英雄...:)

I'm out of options .. Anybody that has tips, please be my hero ... :)

Thanx and regards,

Thanx and regards,

Gerard。

编辑:我尝试过所有排序btw中的状态字段值,但没有运气:(

Edit: I tried the status field value in all sort btw, but no luck :(

推荐答案

我会使用 render_to_string HttpResponseNotFound ,例如 return HttpResponseNotFound(render_to_string('404.html'))

这篇关于Django自定义处理程序404显示404但给出标题200的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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