Django自定义--404页面

时间:2022-11-07 22:51:17

自定义错误页面

常见的错误页面

  • 400 bad request
  • 403 HTTP Forbidden
  • 404 page not found
  • 500 server error

自定义错误页面

  • 配置setting
    DEBUG=True,Django会显示默认错误页面,我们要自定义,所以修改为DEBUG=False
    如果这时启动项目会提示:CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False.
    这是因为DEBUG=True,ALLOWED_HOSTS会验证['localhost','127.0.0.1','[::1]'],DEBUG=False,就必须填写ALLOWED_HOSTS.
    指定ALLOWED_HOSTS=['*']就可以了

  • 编写错误处理view
def page_not_found(request):
        from django.shortcuts import render_to_response
        response = render_to_response('404.html', {})
        response.status_code = 404
        return response
def page_error(request):
        from django.shortcuts import render_to_response
        response = render_to_response('500.html', {})
        response.status_code = 500
        return response
def method_not_allowed(request):
        from django.shortcuts import render_to_response
        response = render_to_response('403.html', {})
        response.status_code = 403
        return response
def bad_request(request):
        from django.shortcuts import render_to_response
        response = render_to_response('400.html', {})
        response.status_code = 400
        return response
  • 配置url映射
handler400 = 'app_name.views.bad_request'
handler404 = 'app_name.views.page_not_found'
handler500 = 'app_name.views.page_error'
handler403 = 'app_name.views.method_not_allowed'
  • 创建页面
    在templates下建立相应的error.html
    下面是我的公益404页面的设置
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>公益404页面</title>
    </head>
    <body>
        <script type="text/javascript"
            src="http://www.qq.com/404/search_children.js"
            charset="utf-8" ></script>
    </body>
</html>