Skip to content

Returning an actual proper real life HTTP code from a Django error page

Go to a non existent page on a Django site and you will (hopefully) be met with a friendly error page telling you not to panic, everything is OK and all you’ve done is mistyped the URL or something.

If it’s your thing, you may be interested enough to look see what the actual HTTP code for the page is in the header; chances are that it will be a 200 rather than a 404 as the default handler just passes the dealings onto the HttpResponse class.

Generally speaking this is fine, but there are situations where an accurate code would be very handy, as I found out the other day when I was trying to detect whether a file had been uploaded to a remote server. Scraping the resultant HTML for “Page not found” is not my idea of a robust solution.

So, instead, pass the error page’s HTML into the respective class by putting something like this in

handler404 = 'urls.return_404'
handler500 = 'urls.return_500'

def return_404(request):
	return HttpResponseNotFound(

def return_500(request):
	return HttpResponseServerError(

Fullest of props to PiotrLegnica at Stack Overflow for this most elegant of solutions.

Edit: After further examination (see the comments) the default handlers do act as expected, but you’re still restricted to where you put your error templates, i.e. the root of the templates directory.
To my mind, it’s neater if you can specify a dedicated location.