使用-> DEBUG = True在Django中自定义404和500页

时间:2019-08-21 18:43:33

标签: django python-3.x sqlite django-rest-framework django-views

我想向客户展示我的网站示例,但还没有完成,但是对于我来说,隐藏错误并且不显示代码库(如果在开发中发生服务器错误时django会这样做)非常重要。模式。像这样-Django depicting what went wrong

我也不能将DEBUG = False设置为那样,因为在这种情况下,由于当前正在本地提供媒体文件,所以不会显示它们。如果DEBUG = False,则不会提供该服务。

因此,有一种方法可以使用DEBUG = False在本地提供媒体文件,或者使用DEBUG = True来显示自定义404和500页。

2 个答案:

答案 0 :(得分:1)

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

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),
    #.....
]

更新:

我没有提到它,但是您需要在模板目录中拥有自定义的404.html500.html模板。

答案 1 :(得分:1)

我建议您替换标准的Django 404页面 TEMPORARILY

在您的虚拟环境中,可以在(yourenvironmentname)/lib/python3.8/site-packages/django/views/templates上找到Django 404模板的路径,名称分别为technical_404.html和technical_500.html。

将以下文件替换为您的自定义404和500页。

相关问题