django 中的自定义 404 和 500 页面 -> DEBUG = True

Dee*_*ant 3 sqlite django django-views python-3.x django-rest-framework

我想向客户展示我的网站示例,它还没有完全完成,但是对我来说隐藏错误并且不显示我的代码库非常重要,如果在开发模式下发生服务器错误,django 会执行哪些操作。就像这样 - Django 描述出了什么问题

另外,我无法将 DEBUG = False 设为 False,因为在这种情况下,媒体文件不会显示,因为它们当前在本地提供。如果 DEBUG = False,则不会提供服务。

那么有没有一种方法可以在 DEBUG = False 的情况下在本地提供媒体文件,或者在 DEBUG = True 的情况下显示自定义 404 和 500 页面。

小智 6

只需将其添加到您的网址中即可:

import django

def custom_page_not_found(request):
    return django.views.defaults.page_not_found(request, None)

def custom_server_error(request):
    return django.views.defaults.server_error(request)

urlpatterns = [
    # .....
    path("404/", custom_page_not_found),
    path("500/", custom_server_error),
    #.....
]
Run Code Online (Sandbox Code Playgroud)

更新:

我没有提到,但您需要在模板目录中包含自定义404.html和模板。500.html