Django3关闭Debug后自定义404页跳转至500错误的异常参数问题
问题解决:Debug=False时Django返回500而非自定义404页面
问题分析
当前核心问题有两点:
handler404导入路径错误,导致Django无法识别自定义404视图- 自定义404视图的参数结构不符合Django要求,触发服务器500错误
解决方案步骤
1. 修正handler404的导入与配置
在Django 3.1及以上版本,handler404 需要从django.urls导入,而非django.conf.urls。修改项目主urls.py:
from django.urls import handler404 handler404 = 'myproject.views.custom_page_not_found'
2. 调整自定义404视图的参数结构
Django要求自定义404视图必须接收exception必填参数,且需放在默认参数之前。修改views.py中的视图:
from django.shortcuts import render def custom_page_not_found(request, exception, template_name="errors/404.html"): return render(request, template_name, status=404)
如果不需要动态指定模板,也可以简化为:
from django.shortcuts import render def custom_page_not_found(request, exception): return render(request, "errors/404.html", status=404)
3. 验证基础配置项
- 确保
settings.py中ALLOWED_HOSTS已正确配置(Debug=False时必须设置):ALLOWED_HOSTS = ['localhost', '127.0.0.1', '你的域名'] - 确认
errors/404.html模板文件存在于项目模板目录中,文件权限正常。
验证结果
完成上述修改后,设置Debug=False并访问不存在的路径,即可正常返回自定义404页面,不再触发500服务器错误。
内容的提问来源于stack exchange,提问作者Zaeem Akhtar
相关产品推荐
相关产品推荐

