【问题标题】:How to specify a custom 404 view for Django using Class Based Views?如何使用基于类的视图为 Django 指定自定义 404 视图?
【发布时间】:2013-02-15 11:18:58
【问题描述】:

使用 Django,您可以通过在根 urls.py 中执行此操作来覆盖默认的 404 页面:

handler404 = 'path.to.views.custom404'

在使用基于类的视图时如何做到这一点?我想不通,文档似乎什么也没说。

我试过了:

handler404 = 'path.to.view.Custom404.as_view'

【问题讨论】:

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


    【解决方案1】:

    没关系,我忘了试试这个:

    from path.to.view import Custom404
    handler404 = Custom404.as_view()
    

    现在看起来很简单,它可能不值得在 StackOverflow 上提问。

    【讨论】:

    • 这似乎对我们不起作用。我得到ContentNotRenderedError: The response content must be rendered before it can be iterated over.
    • @NicolasBouliane 我有同样的错误。你解决了这个问题吗?
    • 直接拨打.render()就可以了。
    • 我认为只需覆盖dispatch 方法并返回您想要的响应就足够了。您不必处理render 或其他任何事情。
    【解决方案2】:

    通过在我的自定义 404 CBV 中添加以下代码来使其工作(在其他 StackOverflow 帖子中找到:Django handler500 as a Class Based View

    from django.views.generic import TemplateView
    
    
    class NotFoundView(TemplateView):
        template_name = "errors/404.html"
    
        @classmethod
        def get_rendered_view(cls):
            as_view_fn = cls.as_view()
    
            def view_fn(request):
                response = as_view_fn(request)
                # this is what was missing before
                response.render()
                return response
    
            return view_fn
    

    在我的根 URLConf 文件中,我有以下内容:

    from apps.errors.views.notfound import NotFoundView
    
    handler404 = NotFoundView.get_rendered_view()
    

    【讨论】:

    • 小心,您应该返回 404 状态,而不仅仅是显示看起来像它的模板。你应该添加response.status_code = 404
    【解决方案3】:

    在您的主要urls.py 中,您只需添加from app_name.views import Custom404 然后设置handler404 = Custom404.as_view()。 它应该工作

    【讨论】:

    • 这似乎从 2021 年 Django 3.1.4 开始有效。似乎不再需要其他答案中的解决方法。
    猜你喜欢
    • 2013-10-09
    • 2019-05-22
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    • 2022-01-24
    • 2015-05-17
    • 2013-03-08
    相关资源
    最近更新 更多