Skip to content

Instantly share code, notes, and snippets.

@revolunet
Created February 3, 2011 17:04
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save revolunet/809780 to your computer and use it in GitHub Desktop.
Save revolunet/809780 to your computer and use it in GitHub Desktop.
add context to your django error pages
#
# by default, django 404 and 500 pages dont pass context to templates.
# as you almost *always* need context variables in your custom
# 404/500 templates, you might need MEDIA_URL for example
#
# you need to create a custom view for errors and register it in your urls.py
#
# in urls.py add :
#
# handler500 = handler404 = views.server_error
#
#
def server_error(request, template_name='500.html'):
from django.template import RequestContext
from django.http import HttpResponseServerError
t = get_template(template_name)
return HttpResponseServerError(t.render(RequestContext(request)))
@oliverseal
Copy link

This old gist is still awesome. The beauty of HttpResponseServerError that doesn't seem to be documented (that I can see) is that it will still send emails to ADMINS if you use if for handler500.

@bharling
Copy link

exactly what i was after!

@lquixada
Copy link

lquixada commented Jul 3, 2014

works great but you missed to import the loader from django.template, this way you can call loader.get_template correctly

@chamalis
Copy link

chamalis commented Jun 17, 2017

Thank you for the snippet. Let me ask something:
What is the purpose of positional argument: template_name?
Since you define

handler500 = handler404 = views.server_error

Isn't this always going to be 500.html, in any case, whatever the exception?

@therearesomewhocallmetim

As of Django 1.11 i get {TypeError}context must be a dict rather than RequestContext.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment