Pretty Django Error Pages

Continuing on with the simple tricks that make everyone’s life a little bit better, I know a lot of people hate that Django’s 500 pages don’t get rendered as a RequestContext. This means that if you have context processors (like one that sets a MEDIA_URL), they don’t get called. This was causing our 500 pages not only to make users sad because something broke, but knock them out of context becaue our entire design blew up.

Luckily, Django makes it incredibly simple to redefine your 500 handler in your URLConf. Most pythonistas know that import * is a bad thing, but it is standard in the Django community in your URLConf to do a from django.conf.urls.defaults import *. This has the effect of pulling in Django’s default handler500 function. So if you want to override Django’s default, you simply set it up like so.

from django.conf.urls.defaults import *
handler500 = ''

Then you simply define a server_error view that renders the error page with a RequestContext.

from django.shortcuts import render_to_response
from django.template import RequestContext

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

    Templates: `500.html`
    Context: None
    return render_to_response(template_name,
        context_instance = RequestContext(request)

If you’re feeling extra special, you can even change the template rendered. Note that you can also do this for the 404 handler by defining a 404handler in your URLConf in the same fashion. Then you can get pretty error pages!

Hey there! I'm Eric and I work on communities in the world of software documentation. Feel free to email me if you have comments on this post!