【问题标题】:Django 3.x - Custom Error Page is showing a 500 when it should be a 404Django 3.x - 自定义错误页面在应该是 404 时显示 500
【发布时间】:2021-07-03 02:21:12
【问题描述】:

更新:添加了我正在访问的引发错误的代码

对于我正在处理 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"

这是 views.py 中我正在访问但要访问 wiki/C 的函数:

#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,但我没有更改任何内容......这是一个单独的问题):

【问题讨论】:

  • 设置DEBUG=True 并尝试访问该页面。你会看到/wiki/C有什么问题
  • 那个页面只是一个触发错误的例子,DEBUG True显示404就好了。我正在测试将 DEBUG 设置为 false 的 404 错误功能
  • 将其更改为 true 并输入错误的 url 会抛出:“解码为 str:需要一个类似字节的对象,找到 NoneType”。那是什么?
  • 是的,这是一个异常/错误,因此它应该显示 500 页,而不是 404
  • 500 表示你的程序搞砸了。保持调试模式打开,直到您修复了异常的原因。您尚未提供导致错误的源代码部分,因此我们无法进一步帮助您。当您的代码了解到用户正在尝试访问一个不存在的页面(从您的错误中,可能使用类似if foo is None 的内容),提出django.http.Http404

标签: python django cs50


【解决方案1】:

您的代码可能有问题。 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

【讨论】:

    【解决方案2】:

    想通了。谢谢你。

    我用来抓取页面的函数出现错误。在查找特定 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 搞砸了,只是我,哈哈

    【讨论】:

    • return render(req, template) 只是绘制 404 页面,但实际上并不返回 404 状态。如果客户正在查看状态码,他们会认为一切正常,因为他们收到 200 OK(带有一些文本)。确保使用return render(req, template, status=404) 返回正确的状态代码,或者最好引发我上面显示的Http404 快捷方式异常。这是Django tutorial 向您展示如何正确操作。
    • 啊,这更有意义。我将编辑代码以反映这一点
    猜你喜欢
    • 2013-07-13
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多