我正在学习Django教程的第五部分:测试。我遇到了一个问题,当我使用DetailView和ListView“快捷”视图来因式分解代码(如教程中建议的那样)时,当显示404页面时,返回的是200状态码。我做错了什么吗?教程说状态码应该是404。
谢谢!
谢谢!
return HttpResponse(content=template.render(context), content_type='text/html; charset=utf-8', status=404)
# 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)
秘密在于最后一行:status=404
希望这有所帮助!
期待社区对这种方法的贡献。=)
你可以
return HttpResponseNotFound(render_to_string('404.html'))
取而代之。
http404
。是的,如果您直接提供404.html
,它会被视为200
,正如您所理解的那样,我刚刚为您点了赞。尝试发布您的解决方案? - CppLearner