简体   繁体   中英

Django HTTP 500 Error

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...

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM