在Django中返回HttpResponseNotFound和引发Http404有什么区别? [英] What's the difference between returning a `HttpResponseNotFound` and raising a `Http404` in Django?

查看:125
本文介绍了在Django中返回HttpResponseNotFound和引发Http404有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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?

推荐答案

An 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有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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