Search code examples
djangodjango-templateshttp-status-code-404django-staticfiles

Using static files in custom 404/500 pages in Django


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.


Solution

  • 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