Reputation: 1489
I am creating a custom HTTP 500 error template. Why is it Django shows it when i raise an exception and not when I return HttpResponseServerError (I just get the default browser 500 error)? I find this behaviour strange...
Upvotes: 9
Views: 21072
Reputation: 2468
As of Django 2+ all you need to do is put the corresponding error templates in your base templates folder. Django will automatically render them before rendering the default.
https://docs.djangoproject.com/en/2.0/ref/views/#error-views
In your case just drop your template '500.html' (or '404.html') into /templates
Upvotes: 0
Reputation: 22808
Put this below in the 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 simple like that.
Upvotes: 2
Reputation: 7706
The HttpResponseServerError
inherits from HttpResponse
and is actually quite simple:
class HttpResponseServerError(HttpResponse):
status_code = 500
So let's 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 by default content
is empty.
Now, let's take a look at how it is called by Django itself (an 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 produce a server error, the template named 500.html is used, but when you simply return HttpResponseServerError
the content is empty and the browser falls back to it's default page.
Upvotes: 11
Reputation: 772
Have you tried with another browser ? Is your custom error page larger than 512 bytes ? It seems some browsers (including Chrome) replace errors page with their own when the server's answer is shorter than 512 bytes.
Upvotes: 1