Reputation: 1062
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'
Upvotes: 15
Views: 7809
Reputation: 379
In your main urls.py
you can just add from app_name.views import Custom404
and then set handler404 = Custom404.as_view()
.
It should work
Upvotes: 1
Reputation: 106
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()
Upvotes: 4
Reputation: 1062
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.
Upvotes: 31