Python Django 自定义 404 页面不起作用

问题描述 投票:0回答:1

我在这里基本上尝试了两种解决方案。第一个:
在根模板目录中创建了 404.html,该目录应该被 django 识别。顺便说一下,在settings.py中定义了它: 'DIRS': [BASE_DIR / '模板'], 我尝试过的第二个解决方案:
在 urls.py 中:

from django.conf.urls import handler404
handler404 = 'pdfapp.views.not_found'

在views.py中:

def not_found(request, exception):
    return render(request, 'partials/not_found.html', status = 404)

这些解决方案都不起作用。 YouTube 视频和其他形式都无法帮助我解决问题。

注意:我的DEBUG设置为False
python django django-forms django-templates http-status-code-404
1个回答
0
投票

要使用 404、500 和其他错误代码的自定义模板,您必须执行以下几个步骤:

  1. 在任何 django 应用程序中添加自定义模板(示例中的用户)-> 模板文件夹:

    用户/模板/用户/404.html

  2. 在 urls.py(公共 url)中为它们添加处理程序

    handler404 = 'users.views.custom_page_not_found_view'

    handler500 = 'users.views.custom_error_view'

  3. 添加您的自定义视图:users/views.py

   def custom_page_not_found_view(request, exception):
   return render(request, "users/404.html", {})


  def custom_error_view(request, exception=None):
    return render(request, "users/500.html", {})
  1. 添加 debug=False 以显示自定义页面
© www.soinside.com 2019 - 2024. All rights reserved.