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

Django 3生产环境中自定义404页面的正确实现方法

Django 自定义404错误页面正确实现步骤

1. 根路由配置

首先在**项目根目录的urls.py**中声明404错误处理函数,该配置放在子应用urls.py中不会生效:

# 项目根urls.py
from django.contrib import admin
from django.urls import path
# 导入自定义的404处理视图
from mysite.views import page_not_found

urlpatterns = [
    path('admin/', admin.site.urls),
    # 其余业务路由
]

# 绑定404错误处理器
handler404 = page_not_found

注意:DEBUG = True时自定义404不会生效,Django会默认展示调试错误页,只有DEBUG = False时才会触发自定义错误页

2. 编写404处理视图

你之前返回文本路径的问题,是因为错误地把模板路径直接传给了HttpResponseNotFound,正确写法有两种:

写法一(推荐,最简洁)

给render方法传入status参数直接指定状态码为404即可:

# mysite/views.py
from django.shortcuts import render

# 注意必须带exception参数,Django3.x+默认会传入异常对象作为第二个参数
def page_not_found(request, exception):
    return render(request, '404_error.html', status=404)

写法二(使用HttpResponseNotFound实现)

需要先手动渲染模板内容再传入HttpResponseNotFound:

from django.http import HttpResponseNotFound
from django.template import loader

def page_not_found(request, exception):
    template = loader.get_template('404_error.html')
    context = {}
    return HttpResponseNotFound(template.render(context, request))

常见返回500错误排查方向

  • 视图函数缺少exception参数,导致参数不匹配触发服务端错误
  • 模板路径配置错误:检查settings.py中TEMPLATES的DIRS配置是否包含404_error.html存放目录,模板文件名拼写错误也会触发500
  • 模板本身存在语法错误:如果404模板内部有语法错误、引用了不存在的变量/过滤器,渲染时会返回500

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 23:06:03