【问题标题】:Using static files in custom 404/500 pages in Django在 Django 的自定义 404/500 页面中使用静态文件
【发布时间】:2013-02-13 19:53:56
【问题描述】:

我想在我创建的自定义404/500 页面上使用一些自定义 CSS 和图像。不过,Django 并没有在这些页面中包含 STATIC_URL 变量。

实现这一目标的最佳方法是什么?我还尝试制作自定义 404/500 视图并渲染任意 HTML 文件,但效果并不理想。

【问题讨论】:

    标签: django django-templates http-status-code-404 django-staticfiles


    【解决方案1】:

    我会这样做:

    # 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默认不这样做的原因:

    “默认的 500 视图不向 500.html 模板传递任何变量,并使用空 Context 进行渲染以减少出现额外错误的机会。”

    -- Adrian Holovaty, Django documentation

    【讨论】:

    • 那么我将如何引用我的静态文件?
    • 这会将STATIC_URL 添加到模板的上下文中。所以你可以像往常一样使用它。
    【解决方案2】:

    我遇到了同样的问题,并找到了一个不需要自定义模板或处理程序的解决方案。从 Django 1.4 开始,您可以使用标签 get_media_prefix 和 get_static_prefix 来访问不在上下文中的 MEDIA_URL 和 STATIC_URL。

    在我的特定情况下(Django 1.5),我想访问我的页面 500.html 中的一些静态图像。我只是在模板的开头添加了

    {% load static %} 
    

    然后获取带有这些标签的媒体和静态url

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

    你可以在这里找到官方文档:https://docs.djangoproject.com/en/1.5/ref/templates/builtins/#get-static-prefix

    【讨论】:

      【解决方案3】:

      我相信您只需要覆盖默认的 404/500 错误处理。这应该可以帮助您开始:

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

      【讨论】:

      • 当您尝试在自定义视图中包含 {% load static from staticfiles %} 时会发生什么?
      猜你喜欢
      • 2019-12-27
      • 2016-09-02
      • 2013-07-13
      • 2013-08-03
      • 2013-07-25
      • 2011-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多