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

北城余情 提交于 2019-12-12 08:27:05

问题


Using Django, you can override the default 404 page by doing this in the root urls.py:

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'

回答1:


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.




回答2:


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)

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:

from apps.errors.views.notfound import NotFoundView

handler404 = NotFoundView.get_rendered_view()


来源:https://stackoverflow.com/questions/15149555/how-to-specify-a-custom-404-view-for-django-using-class-based-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!