django自定义错误处理
要实现自定义错误处理的功能,总共分4步:
1.创建html错误页
2.配置settings ,当DEBUG=True,则不会生效
3.编写视图
4.配置url
views.py def page_not_found(request,exception): #404 return render(request,"blog/404.html",status=404) def page_error(exception): return render("blog/500.html",status=500) def permission_denied(request,exception): #403 return render(request, "blog/403.html",status=403) def bad_request(request,exception): #400 return render(request, "blog/400.html",status=400)
主程序下urls.pyhandler400 = views.bad_request handler403 = views.permission_denied handler404 = views.bad_request handler500 = views.page_error
然后运行:
过程中可能遇到的报错:
# ERRORS:?: (urls.E007) The custom handler500 view ‘blog.views.page_error‘ does not take the correct number of arguments (request).解决:视图函数中不要request参数
def page_error(exception): #500 return render("blog/500.html")
# ERRORS:?: (urls.E007) The custom handler403 view ‘blog.views.permission_denied‘ does not take the correct number of arguments (request, exception).
解决:视图函数中加上exception参数,虽然没什么用
def permission_denied(request,exception): #403 return render(request, "blog/403.html")