在Django的自定义404/500页面中使用静态文件 [英] Using static files in custom 404/500 pages in Django
问题描述
我想在自定义的404/500页面上使用一些自定义的CSS和图像。 Django不包括这些页面中的STATIC_URL变量。什么是最好的方式来完成这个?我还尝试制作一个自定义的404/500视图并呈现任意的HTML文件,但并没有如此出色。
I would like to use some custom CSS and images on my custom 404/500 pages that I made. Django doesn't include the STATIC_URL variable in those pages though. What would be the best way to accomplish this? I also tried making a custom 404/500 view and rendering an arbitrary HTML file but it didn't work out so great.
推荐答案
我将如何做:
# urls or settings
handler500 = 'mysite.views.server_error'
# views
from django.shortcuts import render
def server_error(request):
# one of the things ‘render’ does is add ‘STATIC_URL’ to
# the context, making it available from within the template.
response = render(request, '500.html')
response.status_code = 500
return response
值得一提的是,Django默认情况下不会执行此操作:
It's worth mentioning the reason Django doesn't do this by default:
默认500视图将没有任何变量传递给500.html模板,并使用空的上下文来呈现,以减少额外错误的机会。
"The default 500 view passes no variables to the 500.html template and is rendered with an empty Context to lessen the chance of additional errors."
这篇关于在Django的自定义404/500页面中使用静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!