【问题标题】:Django, creating a custom 500/404 error pageDjango,创建自定义 500/404 错误页面
【发布时间】:2013-07-13 19:55:41
【问题描述】:

按照教程找到here,我无法创建自定义的 500 或 404 错误页面。如果我确实输入了错误的 url,该页面会给我默认的错误页面。有什么我应该检查的东西会阻止自定义页面出现吗?

文件目录:

mysite/
    mysite/
        __init__.py
        __init__.pyc
        settings.py
        settings.pyc
        urls.py
        urls.pyc
        wsgi.py
        wsgi.pyc
    polls/
        templates/
            admin/
                base_site.html
            404.html
            500.html
            polls/
                detail.html
                index.html
        __init__.py
        __init__.pyc
        admin.py
        admin.pyc
        models.py
        models.pyc
        tests.py
        urls.py
        urls.pyc
        view.py
        views.pyc
    templates/
    manage.py

在 mysite/settings.py 我启用了这些:

DEBUG = False
TEMPLATE_DEBUG = DEBUG

#....

TEMPLATE_DIRS = (
    'C:/Users/Me/Django/mysite/templates', 
)

在 mysite/polls/urls.py 中:

from django.conf.urls import patterns, url

from polls import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
    url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
    url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)

我可以发布任何其他必要的代码,但是如果我使用错误的 url,我应该如何更改才能获得自定义 500 错误页面?

编辑

解决方案: 我有一个额外的

TEMPLATE_DIRS

在我的 settings.py 中,这是导致问题的原因

【问题讨论】:

标签: python django django-templates http-status-code-404


【解决方案1】:

在您的主要views.py 下添加您自己的以下两个视图的自定义实现,并使用您的设置模板 404.html500.html想要显示。

使用此解决方案,无需向urls.py 添加自定义代码

代码如下:

from django.shortcuts import render_to_response
from django.template import RequestContext


def handler404(request, *args, **argv):
    response = render_to_response('404.html', {},
                                  context_instance=RequestContext(request))
    response.status_code = 404
    return response


def handler500(request, *args, **argv):
    response = render_to_response('500.html', {},
                                  context_instance=RequestContext(request))
    response.status_code = 500
    return response

更新

handler404handler500 是在django/conf/urls/__init__.py 中找到的导出的Django 字符串配置变量。这就是上述配置有效的原因。

要使上述配置生效,您应该在 urls.py 文件中定义以下变量,并将导出的 Django 变量指向定义这些 Django 功能视图的字符串 Python 路径,如下所示:

# project/urls.py

handler404 = 'my_app.views.handler404'
handler500 = 'my_app.views.handler500'

Django 2.0 更新

处理程序视图的签名在 Django 2.0 中已更改: https://docs.djangoproject.com/en/2.0/ref/views/#error-views

如果您使用上述视图,handler404 将失败并显示消息:

“handler404() 得到了一个意外的关键字参数‘异常’”

在这种情况下,像这样修改您的视图:

def handler404(request, exception, template_name="404.html"):
    response = render_to_response(template_name)
    response.status_code = 404
    return response

【讨论】:

  • 我想知道的另一件事——如果您使用管理后端并想为它们使用单​​独的模板怎么办?据我所知,管理员没有要覆盖和放入这段代码的views.py。
  • @GravityGrave 500 template 不会呈现 request.user,因为它正在报告 500 服务器错误,因此服务器无法提供任何服务。
  • 在 django 1.9 中对我不起作用;(也许我做错了什么。handler404 是 django 保留名称吗?django 怎么知道它应该调用那个视图?
  • 我根据您的评论更新了答案。很抱歉更新这么晚。我希望这会有所帮助。
  • render_to_response 在 Django 3.0 中被 render 取代,它自动使用 RequestContext,简化了这个答案的示例代码
【解决方案2】:

官方回答:

这里是关于如何设置自定义错误视图的官方文档的链接:

https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views

它说在你的 URLconf 中添加这样的行(将它们设置在其他任何地方都没有效果):

handler404 = 'mysite.views.my_custom_page_not_found_view'
handler500 = 'mysite.views.my_custom_error_view'
handler403 = 'mysite.views.my_custom_permission_denied_view'
handler400 = 'mysite.views.my_custom_bad_request_view'

您也可以通过修改设置CSRF_FAILURE_VIEW来自定义CSRF错误视图。

默认错误处理程序:

值得阅读默认错误处理程序的文档,page_not_foundserver_errorpermission_deniedbad_request。默认情况下,如果他们能找到这些模板,他们将分别使用它们:404.html500.html403.html400.html

因此,如果您只想制作漂亮的错误页面,只需在TEMPLATE_DIRS 目录中创建这些文件,您根本不需要编辑 URLConf。阅读文档以查看可用的上下文变量。

在 Django 1.10 及更高版本中,默认的 CSRF 错误视图使用模板 403_csrf.html

问题:

不要忘记DEBUG 必须设置为 False 才能使它们工作,否则将使用正常的调试处理程序。

【讨论】:

  • 我确实添加了,但它不起作用。在我的视图中添加了 handler404 和其他指向正确位置的人,但它不起作用,仍然看到默认的 404。是的,我处于 ​​Debug False 模式并使用 1.9
  • 使用 Django 1.9 并简单地添加 500.html 等模板会显示它们而不是标准页面。很容易修复。
  • Gotcha 帮助了我。它通过在我的 settings.py 中进行这些更改,设置 DEBUG=False 和 ALLOWED_HOSTS = ['0.0.0.0'] 来接受来自任何客户端的 http 请求。
  • 以防万一其他人想知道 URLconf 到底在哪里,here it is
  • @ArthurTarasov 是的,最好参考 urls.py 文件哈哈。
【解决方案3】:

在 urls.py 中添加这些行

urls.py

from django.conf.urls import (
handler400, handler403, handler404, handler500
)

handler400 = 'my_app.views.bad_request'
handler403 = 'my_app.views.permission_denied'
handler404 = 'my_app.views.page_not_found'
handler500 = 'my_app.views.server_error'

# ...

并在views.py中实现我们的自定义视图。

views.py

from django.shortcuts import (
render_to_response
)
from django.template import RequestContext

# HTTP Error 400
def bad_request(request):
    response = render_to_response(
        '400.html',
        context_instance=RequestContext(request)
        )

        response.status_code = 400

        return response

# ...

【讨论】:

【解决方案4】:

Django 3.0+ 4.0+

这里是link如何自定义错误视图

这里是link如何渲染视图

urls.py(主要的,在项目文件夹中),放:

handler404 = 'my_app_name.views.custom_page_not_found_view'
handler500 = 'my_app_name.views.custom_error_view'
handler403 = 'my_app_name.views.custom_permission_denied_view'
handler400 = 'my_app_name.views.custom_bad_request_view'

并在提到的应用程序(my_app_name)中输入views.py

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

def custom_error_view(request, exception=None):
    return render(request, "errors/500.html", {})

def custom_permission_denied_view(request, exception=None):
    return render(request, "errors/403.html", {})

def custom_bad_request_view(request, exception=None):
    return render(request, "errors/400.html", {})

注意:errors/404.html 是您将文件放入项目(而不是应用程序)模板文件夹时的路径templates/errors/404.html,因此请将文件放在您想要的位置并写入正确的路径。

注意 2:页面重新加载后,如果您仍然看到旧模板,请更改 settings.py DEBUG=True,保存,然后再次更改为 False 并再次保存(这将重新启动服务器并收集新模板文件)。

【讨论】:

  • 额外说明:如果您在DEUB=False 中运行,您的静态文件可能无法提供,因此您无法预览自定义错误模板更改。无论如何,使用./manage.py runserver --insecure 强制 django 为他们服务。
  • 解释得很好!
  • 您需要在 render() 调用中添加status=&lt;status_code&gt; 参数,否则您将在响应中获得状态 200。例如。 status=500 500 页。
  • 是的。非常重要,无论您拥有什么 404 页面以及它们的设置有多好,您都需要禁用 DEBUG 才能看到您的自定义 404 页面,这更像是一个仅用于生产的功能(404 页面)
【解决方案5】:

从您引用的页面:

当您从视图中引发 Http404 时,Django 将加载一个专用于处理 404 错误的特殊视图。它通过在您的根 URLconf 中查找变量 handler404 来找到它(并且仅在您的根 URLconf 中;在其他任何地方设置 handler404 将无效),它是 Python 点分语法中的字符串 - 与普通 URLconf 回调使用的格式相同。 404 视图本身并没有什么特别之处:它只是一个普通视图。

所以我相信你需要在你的 urls.py 中添加这样的东西:

handler404 = 'views.my_404_view'

handler500 类似。

【讨论】:

  • 迈克看起来怎么样?今天是我使用 Django 的第一天,我仍然坚持不懈
  • @JimRilye 您需要在视图中添加合适的 500 函数,然后使用该变量引用它。因此,在您的 urlpatterns = ... 行上方,添加一行 handler500 = 'views.handle500',然后将 def handle500(request): 添加到显示您的 500.html 的 views.py 中。
【解决方案6】:

如果您只需要在DEBUG = False 时为您的网站显示一些带有花哨错误消息的自定义页面,然后在您的模板目录中添加两个名为 404.html 和 500.html 的模板,它会自动选择此自定义引发 404 或 500 时的页面。

【讨论】:

  • 这项工作只是确保您在settings.py 的模板列表中有类似'DIRS': [os.path.join(BASE_DIR, '&lt;project_name&gt;/templates')] 的内容。
【解决方案7】:

在 Django 3.x 中,接受的答案将不起作用,因为 render_to_response 已被完全删除,并且自接受的答案适用的版本以来已经进行了一些更改。

还有一些其他的答案,但我提出了一个更清晰的答案:

在您的主要urls.py 文件中:

handler404 = 'yourapp.views.handler404'
handler500 = 'yourapp.views.handler500'

yourapp/views.py 文件中:

def handler404(request, exception):
    context = {}
    response = render(request, "pages/errors/404.html", context=context)
    response.status_code = 404
    return response


def handler500(request):
    context = {}
    response = render(request, "pages/errors/500.html", context=context)
    response.status_code = 500
    return response

确保您已将render() 导入到yourapp/views.py 文件中:

from django.shortcuts import render

旁注:render_to_response() 在 Django 2.x 中已弃用,在版本 3.x 中已完全删除。

【讨论】:

    【解决方案8】:

    不需要额外的视图。 https://docs.djangoproject.com/en/3.0/ref/views/

    只需将错误文件放在模板目录的根目录下

    • 404.html
    • 400.html
    • 403.html
    • 500.html

    当 debug 为 False 时它应该使用你的错误页面

    【讨论】:

      【解决方案9】:

      Django 2.* 中,您可以在 views.py

      中使用此构造
      def handler404(request, exception):
          return render(request, 'errors/404.html', locals())
      

      settings.py

      DEBUG = False
      
      if DEBUG is False:
          ALLOWED_HOSTS = [
              '127.0.0.1:8000',
              '*',
          ]
      
      if DEBUG is True:
          ALLOWED_HOSTS = []
      

      urls.py

      # https://docs.djangoproject.com/en/2.0/topics/http/views/#customizing-error-views
      handler404 = 'YOUR_APP_NAME.views.handler404'
      

      通常我创建 default_app 并在其中处理站点范围的错误和上下文处理器。

      【讨论】:

      • 为我工作。但是exception 是什么?
      • 根据文档链接:docs.djangoproject.com/en/2.1/ref/urls/…。它是这样写的:确保处理程序接受请求和异常参数
      • Django 3.0 中为我工作。但是locals() 是什么?该文件仅显示pass
      【解决方案10】:

      settings.py:

      DEBUG = False
      TEMPLATE_DEBUG = DEBUG
      ALLOWED_HOSTS = ['localhost']  #provide your host name
      

      只需在模板文件夹中添加您的 404.html500.html 页面。 从投票应用程序的模板中删除 404.html500.html

      【讨论】:

      【解决方案11】:

      出错,在错误页面上找出django从哪里加载模板。我的意思是路径堆栈。在基础template_dir中添加这些html页面500.html404.html。发生这些错误时,将自动加载相应的模板文件。

      您也可以为其他错误代码添加页面,例如 400403

      希望有帮助!!!

      【讨论】:

        【解决方案12】:

        单行(对于 404 通用页面):

        from django.shortcuts import render_to_response
        from django.template import RequestContext
        
        return render_to_response('error/404.html', {'exception': ex},
                                              context_instance=RequestContext(request), status=404)
        

        【讨论】:

        • 在哪里使用它?
        【解决方案13】:
        # views.py
        def handler404(request, exception):
            context = RequestContext(request)
            err_code = 404
            response = render_to_response('404.html', {"code":err_code}, context)
            response.status_code = 404
            return response
        
        # <project_folder>.urls.py
        handler404 = 'todo.views.handler404' 
        

        这适用于 django 2.0

        确保在应用模板文件夹中包含您的自定义 404.html

        【讨论】:

          【解决方案14】:

          尝试将您的错误模板移至.../Django/mysite/templates/ 吗?

          我对这一点很确定,但我认为这些对于网站来说需要是“全球性的”。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-02-04
            • 1970-01-01
            • 2011-01-23
            • 2015-08-26
            • 2019-12-27
            • 2014-04-07
            相关资源
            最近更新 更多