You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django配置handler500后自定义500错误页不生效该如何解决?

核心问题排查

1. 首要根因:Template.render 参数顺序错误

Django 模板的render()方法参数顺序为先传上下文字典,再传request对象,你当前的代码传参顺序颠倒,会导致custom_500函数本身抛出异常,Django检测到500处理函数自身出错后,会直接 fallback 到默认的极简500错误页,就是你看到的提示内容。

2. 其他可能的配置遗漏

  • 检查handler500是否配置在根urls.py中:也就是settings.ROOT_URLCONF指向的urls文件,不能放在子应用的urls配置里
  • 确认common应用已添加到settings.INSTALLED_APPS列表中,否则Django无法找到common.view_utils.custom_500函数
  • 检查是否存在自定义中间件/第三方异常处理组件拦截了异常,没有将异常向上抛出到Django的全局异常处理流程
  • 确认测试的视图中没有额外的try-except逻辑捕获了你抛出的Error,导致异常无法传递到全局处理器

修正后的代码示例

优先使用django.shortcuts.render快捷方法,避免参数顺序写错:

import sys
import traceback
import logging
from django.shortcuts import render
logger = logging.getLogger(__name__)

def custom_500(request):
    logger.error(sys.exc_info())
    exc_type, exc_value, exc_tb = sys.exc_info()
    return render(
        request,
        '500.html',
        context={
            'exception_value': exc_value,
            'value': exc_type,
            'traceback': traceback.format_exception(exc_type, exc_value, exc_tb)
        },
        status=500
    )

如果要保留原来的loader写法,修正参数顺序即可:

def custom_500(request):
    logger.error(sys.exc_info())
    t = loader.get_template('500.html')
    type, value, tb = sys.exc_info()
    return HttpResponseServerError(t.render(
        {
            'exception_value': value,
            'value': type,
            'traceback': traceback.format_exception(type, value, tb)
        }, 
        request
    ))

内容的提问来源于stack exchange,提问作者Viktor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 19:36:00