How to specify a custom 404 view for Django using

2019-04-05 10:32发布

问题:

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()