python测试开发django-96.404和500页面处理

前言

django 访问一个不存在的 url 地址时出现404,会报一大堆异常的 html 页面。我们可以自定义一个 404 页面,这样看起来页面友好一点。

遇到问题

settings.py 当 DEBUG 设置为 True 的时候

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

访问一个不存在地址:http://localhost:8000/yoyo,404页面

DEBUG = True 是开发者模式,报错的时候方便排错,正式部署一般设置 DEBUG = False

自定义404页面

settings.py 设置 DEBUG = False

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['*']

在 templates 模板下添加 404.html 和 500.html

404.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>404 not found</title>
</head>
<body>
<p>404 not found</p>

</body>
</html>

500.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>500 server error</title>
</head>
<body>
<p>500 server error</p>
</body>
</html>

修改views.py文件,添加2个视图函数

def page_not_found(request, exception):
    return render(request, '404.html')


def page_error(request):
    return render(request, '500.html')

urls.py配置

配置 handler404 = "应用名称.views.函数名称"

# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/

urlpatterns = [
    path('admin/', admin.site.urls),   # 默认admin路径
]

handler404 = 'apiapp.views.page_not_found'
handler500 = 'apiapp.views.page_error'
# 格式为:'app名.views.函数名'

访问404页面

访问一个不存在地址:http://localhost:8000/yoyo/,404页面

DEBUG = False 后如果打开web页面,发现静态资源文件丢失,那是另外一个问题,参考这篇https://www.cnblogs.com/yoyoketang/p/14860180.html

posted @ 2021-06-07 18:54  上海-悠悠  阅读(295)  评论(0编辑  收藏  举报