我正在阅读 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/