Django 404页面返回200状态码

标签 django

我正在阅读 Django 教程并正在进行第 5 部分:测试。我遇到了这样的问题:我使用 DetailView 和 ListView“快捷方式” View 来分解代码(按照教程的建议),但是当显示 404 页面时,会返回 200 状态代码。难道我做错了什么?教程说状态代码应该是 404。

谢谢!

最佳答案

您需要定义 Http header 才能获得 404 状态。

return HttpResponse(content=template.render(context), content_type='text/html; charset=utf-8', status=404)

通知搜索引擎当前页面是 404 页面非常重要。垃圾邮件发送者有时会创建大量 URL,这些 URL 看似会引导您到达某个位置,但随后会为您提供其他内容。他们经常使用许多不同的地址为您提供几乎完全相同的内容。而且由于它对用户不友好,大多数 SEO 指南都会对此进行惩罚。因此,如果您有很多地址显示相同的伪 404 内容,那么对于搜索网站的爬行系统来说,它看起来可能不太好。因此,您需要确保用作自定义 404 的页面具有 404 状态。

如果您正在尝试制作自定义 404 页面,这里是一个好方法:

在应用程序的 urls.py 中添加:

# Imports
from django.conf.urls.static import static
from django.conf.urls import handler404
from django.conf.urls import patterns, include, url
from yourapplication import views

##
# Handles the URLS calls
urlpatterns = patterns('',
    # url(r'^$', include('app.homepage.urls')),
)

handler404 = views.error404

在应用程序的views.py中添加:

# Imports
from django.shortcuts import render
from django.http import HttpResponse
from django.template import Context, loader


##
# Handle 404 Errors
# @param request WSGIRequest list with all HTTP Request
def error404(request):

    # 1. Load models for this view
    #from idgsupply.models import My404Method

    # 2. Generate Content for this view
    template = loader.get_template('404.htm')
    context = Context({
        'message': 'All: %s' % request,
        })

    # 3. Return Template for this view + Data
    return HttpResponse(content=template.render(context), content_type='text/html; charset=utf-8', status=404)

secret 在最后一行:status=404

希望对您有帮助!

我期待看到社区对此方法的意见。 =)

关于Django 404页面返回200状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14085953/

相关文章:

python - Django 1.6 - 消息未显示

python - 无法运行 python manage.py 检查

python-3.x - 合并或联合动态创建的查询集列表 - Django

jquery - 获取 Django 中 HTML 表单中多个按钮之一的 ID

python - 将本地 infile csv 加载到 mysql 数据库失败

javascript - Django 模板变量在脚本标签中无法识别,但在常规 h1 标签中可识别。是什么原因造成的?

python - 使用 html5 输入类型 ='color'

python - 测试中的模型 - Django 1.7 问题

python - 如何停止 Django "app not found"错误?

python - Django 中的所有模型基本上都有分配给对象变量的初始化构造函数吗