如何使用get_object_or_404显示个性化错误

Asi*_*nox 10 django django-templates http-status-code-404

我想知道如何显示个性化的错误get_object_or_404?,我不想要正常的http404页面,我想显示一条消息,结果是无

谢谢 :)

Ara*_*yan 16

get_object_or_404()基本上是一个简单的5行功能.除非您有一些特定的理由使用它,否则只需:

try:
    instance = YourModel.objects.get(pk=something)
except YourModel.DoesNotExist:
    return render_to_response('a_template_with_your_error_message.html')
Run Code Online (Sandbox Code Playgroud)

如果由于某种原因你必须使用get_object_or_404(),你可以尝试将它放在一个try: ... except Http404: ...块中,但老实说,我不能想到一个合理的理由.