django 如何创建一个自定义的404/500错误页面

在您的主要内容下views.py添加您自己的以下两个视图的自定义实现,并设置模板404.html和500.html以及您想要显示的内容。

代码:views.py 

from django.shortcuts import render_to_response
from django.template import RequestContext


def handler404(request, *args, **argv):
    response = render_to_response('404.html', {},                                  context_instance=RequestContext(request))
    response.status_code = 404
    return response


def handler500(request, **argv):
    response = render_to_response('500.html',                                  context_instance=RequestContext(request))
    response.status_code = 500
    return response

handler404和handler500导出了Django字符串配置变量django/conf/urls/__init__.py。这就是上面配置的原因。

要使上述配置生效,您应该在urls.py文件中定义以下变量,并将导出的Django变量指向定义这些Django功能视图的字符串Python路径,如下所示:

在urls.py添加以下代码

from django.conf.urls import (
handler400, handler403, handler404, handler500
)

handler400 = 'my_app.views.bad_request'
handler403 = 'my_app.views.permission_denied'
handler404 = 'my_app.views.page_not_found'
handler500 = 'my_app.views.server_error'

Django 2.0的更新

在Django 2.0中更改了处理程序视图的签名:https: //docs.djangoproject.com/en/2.0/ref/views/#error-views

如果您使用上述视图,handler404将失败并显示以下消息:

“handler404()得到了一个意外的关键字参数'exception'”

在这种情况下修改您的视图,如下所示:

def handler404(request, exception, template_name="404.html"):
    response = render_to_response("404.html")
    response.status_code = 404
    return response

疑难杂症:

不要忘记DEBUG必须设置为False才能使这些工作,否则,将使用正常的调试处理程序。

官方文档:https://docs.djangoproject.com/en/2.2/topics/http/views/#customizing-error-views

相关文章

注:所有源代码均实测运行过。所有源代码均已上传CSDN,请有...
继承APIView和ViewSetMixin;作用也与APIView基本类似,提供...
一、Django介绍Python下有许多款不同的 Web 框架。Django是重...
本文从nginx快速掌握到使用,gunicorn快速掌握到使用,实现小...
uniapp微信小程序订阅消息发送服务通知
Django终端打印SQL语句 1 Setting配置: 2 默认python 使用的...