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?
相关问题
- Django __str__ returned non-string (type NoneType)
- Django & Amazon SES SMTP. Cannot send email
- Django check user group permissions
- Django restrict pages to certain users
- UnicodeEncodeError with attach_file on EmailMessag
相关文章
- Profiling Django with PyCharm
- Why doesn't Django enforce my unique_together
- MultiValueDictKeyError in Django admin
- Django/Heroku: FATAL: too many connections for rol
- Django is sooo slow? errno 32 broken pipe? dcramer
- Django: Replacement for the default ManyToMany Wid
- Upgrading transaction.commit_manually() to Django
- UnicodeEncodeError when saving ImageField containi
In addition to what Daniel said, raising an
Http404
exception can be more flexible in that it allows you to generate a 404 e.g. from a helper function deeper in your call stack (possibly one that usually returns a non-HttpResponse
type) and rely on Python's exception propagation instead of having to create aHttpResponseNotFound
and manually pass it back up to where you were originally crafting your response.An
HttpResponseNotFound
is just like a normalHttpResponse
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.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 - usingHttpResponseNotFound
, in fact. But the convenience is that you're then specifying the template (and view, if you like) in one place.In addtion to what Daniel and esmail said, for reference, this is literally the definition of
HttpResponseNotFound
Django (v1.8):And for good measure, the definition of
Http404
: