【问题标题】:Redirect any urls to 404.html if not found in urls.py in django如果在 django 的 urls.py 中找不到,则将任何 url 重定向到 404.html
【发布时间】:2015-07-25 13:36:20
【问题描述】:

如果 urls.py 中不存在任何类型的 url 模式而不是被 django 显示错误,我如何将任何类型的 url 模式重定向到创建的页面“404.html”页面。

【问题讨论】:

  • 停用DEBUG。这样就可以了。

标签: python regex django django-urls


【解决方案1】:

无需更改您的viewurl 中的任何内容。 只需执行这 2 个步骤,在您的 settings.py 中执行以下操作

DEBUG = False
ALLOWED_HOSTS = ["*"]

在您的应用目录(本例中为 myapp)中,创建myapp/templates/404.html,其中404.html 是您的自定义错误页面。就是这样。

【讨论】:

  • 永远不要在生产中使用 ALLOWED_HOSTS = ["*"]
【解决方案2】:

转到您的项目settings.py 并将DEBUG = True 设置为DEBUG = False 然后 Django 将所有未设置的模式重定向为未找到。

另外如果你想自定义404模板,在你的项目urls.py

设置

handler404 = 'app.views.404_view'

然后在你的项目中view.py

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

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

最后,在您的 templates 添加 404.html 并填写您想要向最终用户展示的内容。

【讨论】:

    【解决方案3】:

    在您的views.py 中,只需添加以下代码(无需更改urls.py 中的任何内容)。

    from django.shortcuts import render_to_response
    from django.template import RequestContext
    
    
    def handler404(request):
        response = render_to_response('404.html', {},
                                  context_instance=RequestContext(request))
        response.status_code = 404
        return response
    

    在模板目录下放一个自定义的 404.html。

    source : click here

    【讨论】:

      【解决方案4】:

      创建一个视图来呈现您创建的 404.html 并将其设置为 urls.py 中的 handler404。

      handler404 = 'app.views.404_view'
      

      如果启用调试,Django 将呈现调试视图。否则,如果它不存在,它将按照 handler404 中指定的方式为所有类型的页面呈现 404 页面。

      Customizing error views 上的 Django 文档。

      查看this 答案以获取完整示例。

      【讨论】:

      • 谢谢,但是有没有办法可以在没有 debug=false 的情况下进行 404 处理,因为它破坏了我的 CSS,因为没有加载静态文件
      • @AnkanKumarGiri 这在this 线程中有很大的解释。请务必阅读所有答案。
      猜你喜欢
      • 2018-07-17
      • 2021-10-17
      • 2018-11-17
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      相关资源
      最近更新 更多