python - Django 3.x - 自定义错误页面在应该是 404 时显示 500
问题描述
更新:添加了我正在访问的引发错误的代码
对于我正在处理 wiki 页面的 CS50 项目,当用户键入 wiki/TITLE 中不存在的页面时,我尝试发送正确的自定义 404 错误,但是当我键入缺少的页面时,Django 抛出500 而不是 404。这是一个常见错误还是我的错误信息有误?Debug 设置为 False,Allowed Hosts 在设置中配置为 ['*']:
这是我在 views.py 中的自定义错误处理程序:
def error_404(request, exception):
context = {}
response = render(request, 'encyclopedia/error_404.html', context=context)
response.status_code = 404
return response
def error_500(request):
context = {}
response = render(request, 'encyclopedia/error_500.html', context=context)
response.status_code = 500
return response
以下是它们在 wiki/urls.py 中的样子:
from django.contrib import admin
from django.urls import include, path
from django.conf.urls import handler404, handler500
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("encyclopedia.urls")),
]
handler404 = "encyclopedia.views.error_404"
handler500 = "encyclopedia.views.error_500"
这是我正在访问但要访问 wiki/C 的 views.py 中的函数:
#function gets entry from index.html's <li>
def entry_page(request, entry):
name = entry # Places the title
print(f"checking the title: {entry}")
text = util.get_entry(entry) # Grabs the entry using the util function
html = md_converter(text)
if text is not None:
return render(request, "encyclopedia/entry.html", {
"title": name,
"entry": html
})
这是我的 urls.py:
from django.urls import path
from . import views
app_name = "encyclopedia"
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:entry>", views.entry_page, name="entry"),
path("wiki/edit/<str:title>", views.edit, name="edit"),
path("search", views.search, name="search"),
path("random", views.random_page, name="random"),
path("create_entry",views.create_entry, name="create_entry")
]
这是终端显示的内容(我的 styles.css 出于某种原因抛出 404,但我没有更改任何内容......这是一个单独的问题):
解决方案
您的代码可能有问题。Django doc清楚地说
The 404 view is also called if Django doesn’t find a match after checking every regular expression in the URLconf.
https://docs.djangoproject.com/en/3.2/ref/views/#error-views
推荐阅读
- r - 得到结果后从 R 中导出数据
- javascript - 将视频锚点的所有实例替换为 iframe
- openiddict - 为所有 openiddict 路由指定 url 前缀
- c - 为什么 qemu 有时会比 ptrace 计数更多有时更少的指令?
- qt - 在 Qwt 图中使用一对一标签
- python - 如何在 2d 列表 python 中找到具有相同变量的值的总和,仅使用列表理解?
- haskell - 在模式匹配的不同情况下推导出不同的类型类约束
- javascript - 如何处理由崩溃导致的 404 页面返回。反应路由器
- swift - 停止在 UITableView 的嵌套 UICollectionView 中播放视频或仅在嵌套结构中的可见单元格上播放
- svelte - Svelte (rollup) - 错误:意外的令牌(请注意,您需要 @rollup/plugin-json 来导入 JSON 文件)