pri*_*stc 14 django templates http-status-code-404
我有一个我在django工作的项目.我有很多例子:
raise Http404("this is an error")
Run Code Online (Sandbox Code Playgroud)
它为我创建了一个很好的404页面,上面写着错误消息"这是一个错误".
我现在想要创建一个自定义错误页面并让它仍然显示消息,但我无法弄清楚如何.
我确定它只是一个模板变量,我需要添加到我的自定义404模板,但我找不到任何文档.
Ala*_*air 10
从Django 1.9开始,异常将传递给page_not_found在您引发时运行的视图Http404.将错误的表示传递给模板,您可以将其包含在模板中:
{{ exception }}
Run Code Online (Sandbox Code Playgroud)
在早期版本中,异常未传递给page_not_found视图,因此没有一种简单的方法可以在模板中包含来自异常的消息.
一种可能性是使用@Euribates在答案中建议的消息框架.另一个是渲染模板并在视图中返回404状态代码,而不是提升Http404.
还有另一种方式.在代码page_not_found的用途RequestContext; 这意味着您可以访问由TEMPLATE_CONTEXT_PROCESSORS条目中定义的所有上下文处理器定义的所有变量settings.py.默认值包括django 消息框架等.
因此,您可以定义要使用的消息messages.error,例如,使用messages变量在模板中显示消息.
换句话说,您可以像这样编写视图:
from django.contrib import messages
from django.http import Http404
from django.template import RequestContext
def my_view(request):
# your code goes here
if something_horribly_wrong_happened():
messages.error(request, 'Somethig horribly wrong happened!')
raise Http404("It doesn't mind whatever you put here")
else:
return render_to_response(
'template.html',
RequestContext(request, locals()),
)
Run Code Online (Sandbox Code Playgroud)
在您的404.html模板中,您应该写一些类似于:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
Run Code Online (Sandbox Code Playgroud)
这是一个有点复杂,但它的优势在于,您可以发送几个消息,甚至使用diferent类型的消息(警告,调试,信息,错误等),您可以在此处详细了解Django的消息框架:将消息框架| Django文档.
| 归档时间: |
|
| 查看次数: |
7408 次 |
| 最近记录: |