Django HTTP Error 500

I am creating my own HTTP 500 error template. Why does Django show this when I throw an exception and not when I return an HttpResponseServerError (I just get the default browser error 500)? I find this behavior strange ...

+8
python django templates
source share
3 answers

HttpResponseServerError inherits from HttpResponse and is actually quite simple:

 class HttpResponseServerError(HttpResponse): status_code = 500 

So take a look at the HttpResponse constructor:

 def __init__(self, content='', *args, **kwargs): super(HttpResponse, self).__init__(*args, **kwargs) # Content is a bytestring. See the `content` property methods. self.content = content 

As you can see the default content empty.

Now let's see how it is called by Django itself (excerpt from django.views.defaults):

 def server_error(request, template_name='500.html'): """ 500 error handler. Templates: :template:`500.html` Context: None """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: return http.HttpResponseServerError('<h1>Server Error (500)</h1>') return http.HttpResponseServerError(template.render(Context({}))) 

As you can see, when you create a server error, a template called 500.html is used, but when you just return an HttpResponseServerError , the content is empty and the browser returns to it by default.

+11
source

Put it below in urls.py.

 #handle the errors from django.utils.functional import curry from django.views.defaults import * handler500 = curry(server_error, template_name='500.html') 

Put 500.html in your templates. Just as easy.

+2
source

Have you tried with another browser? Is your custom error page larger than 512 bytes? It seems that some browsers (including Chrome) replace the error page with their own when the server response is shorter than 512 bytes.

0
source

All Articles