问题描述
显然有两种不同的方法可以在 Django 中返回 404 错误:通过返回 HttpResponseNotFound
对象或通过引发 Http404
异常.虽然我在我的项目中使用了前者,但 Django 的内部视图似乎主要使用后者.除了例外是例外"的口头禅之外,这两种方式之间有什么区别,我应该使用哪种方式?
There are apparently two different ways to return a 404 error in Django: by returning a HttpResponseNotFound
object or by raising an Http404
exception. While I'm using the former in my project, it seems that Django's internal views are mostly using the latter. Apart from the "Exception is exceptional" mantra, what's the difference between both ways and which should I be using?
推荐答案
HttpResponseNotFound
与普通的 HttpResponse
一样,只是它发送错误代码 404.所以它取决于您要在该视图中呈现适当的 404 页面,否则浏览器将显示其自己的默认值.
An HttpResponseNotFound
is just like a normal HttpResponse
except it sends error code 404. So it's up to you to render an appropriate 404 page in that view, otherwise the browser will display its own default.
引发 Http404
异常将触发 Django 调用自己的 404 错误视图.实际上,这只不过是渲染 404.html 模板并发送它 - 实际上使用 HttpResponseNotFound
.但方便的是,您可以在一处指定模板(和视图,如果您愿意).
Raising an Http404
exception will trigger Django to call its own 404 error view. Actually, this does little more than render the 404.html template and send it - using HttpResponseNotFound
, in fact. But the convenience is that you're then specifying the template (and view, if you like) in one place.
这篇关于在 Django 中返回 `HttpResponseNotFound` 和引发 `Http404` 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!