n5321 | 2025年6月27日 16:52

Tags: blogbuilding


404 page 是页面不存在

500 page 是你的后台代码或模板中出现了运行时错误,而你没有处理它,Django 默认就返回了一个“服务器内部错误”的页面。

控制是通过setting.py 中的debug=false or true

实现形式:

  1. 准备404page and 500 page

  2. settings.py 中

    1. X  DEBUG = True 静态语句改动态语句 
    2. DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False'
    3. 设置environment值。

    4. bash复制编辑# Linux/macOS
      export DJANGO_DEBUG=False
      python manage.py runserver

      # Windows CMD
      set DJANGO_DEBUG=False
      python manage.py runserver

      # Windows PowerShell
      $env:DJANGO_DEBUG = "False"
      python manage.py runserver
    5. windows内以上设置OK。ubuntu需要改gunicorn 配置文件。

      1. 编辑 Gunicorn 的 systemd 服务文件

      2. 找到 [Service] 部分,添加:Environment="DJANGO_DEBUG=False"

    6. project directory添加views.py , 添加

      1. from django.shortcuts import render

        def custom_404(request, exception):
          return render(request, 'home/page_error_404.html', status=404)
    7. project urls.py 中添加语句:

      1. handler404 = 'mysite.views.custom_404'
    8. 500page的做法更加单。page命名为500.html ,直接放在template directory下面。(系统自动搜索)


最终效果