大佬教程收集整理的这篇文章主要介绍了Django 3.x - 自定义错误页面显示 500,而它应该是 404,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
更新:添加了我正在访问的引发错误的代码
对于我正在处理 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@R_478_6964@>",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 文档清楚地说
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
,想通了。谢谢你们。
我用来抓取页面的函数有错误。我在查找特定 wiki 条目时没有检查 URL 是否有效。
将 views.py 中的 entry_page 更改为这样就可以了!:
def entry_page(request,entry):
if entry in util.list_entries():
name = entry # Places the title
text = util.get_entry(entry) # Grabs the entry using the util function
html = md_converter(text)
return render(request,"encyclopedia/entry.html",{
"title": name,"entry": html
})
else:
return render(request,"encyclopedia/error_404.html" )
很高兴不是 Django 搞砸了,只是我哈哈
以上是大佬教程为你收集整理的Django 3.x - 自定义错误页面显示 500,而它应该是 404全部内容,希望文章能够帮你解决Django 3.x - 自定义错误页面显示 500,而它应该是 404所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。