Using static files in custom 404/500 pages in Django

烂漫一生 提交于 2019-12-09 17:28:11

问题


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.


回答1:


Here's how I would do it:

# 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

It's worth mentioning the reason Django doesn't do this by default:

“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.”

-- Adrian Holovaty, Django documentation




回答2:


I run into the same problem and found a solution which doesn't need custom templates or handlers. From Django 1.4 on you can use the tags get_media_prefix and get_static_prefix to access MEDIA_URL and STATIC_URL when they are not in the context.

In my particular case (Django 1.5), I wanted to access some static images in my page 500.html. I just added at the beginning of the template

{% load static %} 

and then obtained the media and static urls with these tags

<img src="{% get_media_prefix %}logo.png">
<img src="{% get_static_prefix %}img/error_pages/error.png" style="height:235px;">

You can find the official documentation here: https://docs.djangoproject.com/en/1.5/ref/templates/builtins/#get-static-prefix




回答3:


I believe you're just going to have to override the default 404/500 error handling. This should get you started:

http://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views



来源:https://stackoverflow.com/questions/15121731/using-static-files-in-custom-404-500-pages-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!