简体   繁体   English

如何使用基于类的视图为 Django 指定自定义 404 视图?

[英]How to specify a custom 404 view for Django using Class Based Views?

Using Django, you can override the default 404 page by doing this in the root urls.py :使用 Django,您可以通过在根urls.py执行此操作来覆盖默认的 404 页面:

handler404 = 'path.to.views.custom404'

How to do this when using Class based views?使用基于类的视图时如何执行此操作? I can't figure it out and the documentation doesn't seem to say anything.我想不通,文档似乎什么也没说。

I've tried:我试过了:

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

Never mind, I forgot to try this:没关系,我忘了尝试这个:

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

Seems so simple now, it probably doesn't merit a question on StackOverflow.现在看起来很简单,它可能不值得在 StackOverflow 上提问。

Managed to make it work by having the following code in my custom 404 CBV (found it on other StackOverflow post: Django handler500 as a Class Based View )通过在我的自定义 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

In my root URLConf file I have the following:在我的根 URLConf 文件中,我有以下内容:

from apps.errors.views.notfound import NotFoundView

handler404 = NotFoundView.get_rendered_view()

In your main urls.py you can just add from app_name.views import Custom404 and then set handler404 = Custom404.as_view() .在您的主urls.py您只需添加from app_name.views import Custom404然后设置handler404 = Custom404.as_view() It should work它应该工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Django 中使用基于 Class 的视图制作注册视图? - How to make a signup view using Class based views in Django? 如何使用基于django类的视图和装饰器将数据附加到视图方法? - How to attach data to view methods with django class based views and decorators? Django 如何在基于 class 的视图中传递自定义错误消息 - Django how to pass custom error message in class based views 如何使用基于类的视图制作类别视图以列出Django中具有相关类别的所有帖子 - How can I make category view to list out all the post with related category in Django using class based views Django - 在基于类的视图上使用 reverse() - Django - using reverse() on Class-based views 如何将基于类的视图转换为基于函数的视图? - Django - How can I convert my class-based view to function-based views? - Django 基于Django类的视图 - Django class based views 如何将参数传递给 Django 中基于 Class 的视图? - How to pass a parameter to Class based views in Django? 在Django 1.7中使用多个通用视图和一个基于类的视图中的表单的最佳实践 - Best practices for using multiple generic views and a form within one class based view in Django 1.7 在基于Django类的视图中检查视图方法参数名称 - Check view method parameter name in Django class based views
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM