Passing MEDIA_URL in Django's 500 error view

Published 15th January 2009

The default HTTP 500 error view in Django doesn't pass the RequestContext to templates and thus variables like MEDIA_URL will not be available. If, for example, your error 500 template extends your site's base template, the URI to the CSS style sheets won't be right.

Django doesn't include the RequestContext per default since in case of an HTTP 500 error it's better to pass less variables to lessen the chance of additional errors. However, changing the default error 500 view in Django to pass the MEDIA_URL in the context is easy.

Modifying the default handler

We first need to write a new view which will replace the default one. The following is identical to the default view but with the MEDIA_URL added to the context:

from django.conf import settings
from django import http
from django.template import Context, loader

def server_error(request, template_name='500.html'):
    """
    500 error handler.

    Templates: `500.html`
    Context:
        MEDIA_URL
            Path of static media (e.g. "media.example.org")
    """
    t = loader.get_template(template_name) # You need to create a 500.html template.
    return http.HttpResponseServerError(t.render(Context({
        'MEDIA_URL': settings.MEDIA_URL
    })))

The best place for this view is the views.py file in the project's root directory.

To tell Django to use our view for the HTTP 500 error rather than the default one, we need to set the handler500 variable in the urls.py file to point to the new view:

handler500 = 'projectname.views.server_error'

And that's basically it, we've replaced the default error 500 view with our own one that passes the MEDIA_URL in the context.

To see the error 500 page in action, we just need to create a url pattern for it:

if settings.DEBUG:
    urlpatterns += patterns('',
        (r'^500/$', 'projectname.views.server_error'),
    )