python测试开发django-96.404和500页面处理
2021/6/7 20:53:56
本文主要是介绍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页面
这篇关于python测试开发django-96.404和500页面处理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python