如何在Django自定义404错误模板中显示传递给Http404的消息? [英] How to display the message passed to Http404 in a custom 404 Error template in Django?

查看:103
本文介绍了如何在Django自定义404错误模板中显示传递给Http404的消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我在django工作的项目。有很多情况下,我:

  raise Http404(this is a error)

,它为我创建了一个不错的404页面,并出现了错误消息这是一个错误。



我现在想创建一个自定义的错误页面,并且仍然显示消息,但我无法弄清楚如何。



我确定它只是一个模板变量,我需要添加到我的自定义404模板,但我找不到任何文档。

解决方案

从Django 1.9起,异常传递给 page_not_found 当您提高 Http404 时运行的视图。将错误的表示传递给模板,您可以将其包含在模板中:

  {{exception}} 

在早期版本中,异常未传递给 page_not_found 视图,所以没有一个简单的方法来包含模板中的异常消息。



一种可能性是将消息框架用作@Euribates建议在他们的答案。另一个是渲染一个模板,并在你的视图中返回一个404状态代码,而不是提高 Http404


I have a project that I am working on in django. There are a lot of instances where I:

raise Http404("this is an error")

and it creates a nice 404 page for me with the error message "this is an error" written on it.

I now want to create a custom error page and have it still display the message, but I can't figure out how.

I'm sure it's just a template variable that I need to add to my custom 404 template, but I can't find any documentation for it.

解决方案

As of Django 1.9, the exception is passed to the page_not_found view which runs when you raise Http404. A representation of the error is passed to the template, you can include it in your template with:

{{ exception }}

In earlier versions, the exception was not passed to the page_not_found view, so there wasn't an easy way to include the message from the exception in the template.

One possibility was to use the messages framework as @Euribates suggests in their answer. Another was to render a template and return a 404 status code in your view, instead of raising Http404.

这篇关于如何在Django自定义404错误模板中显示传递给Http404的消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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