How to properly setup custom handler404 in django?

blueFast picture blueFast · Feb 2, 2016 · Viewed 8.4k times · Source

According to the documentation this should be fairly simple: I just need to define handler404. Currently I am doing, in my top urls.py:

urlpatterns = [
    ...
]

handler404 = 'myapp.views.handle_page_not_found'

The application is installed. The corresponding view is just (for the time being I just want to redirect to the homepage in case of 404):

def handle_page_not_found(request):
    return redirect('homepage')

But this has no effect: the standard (debug) 404 page is shown.

The documentation is a bit ambiguous:

  • where should handler404 be defined? The documentation says in the URLconf but, where exactly? I have several applications, each with a different urls.py. Can I put it in any of them? In the top URLconf? Why? Where is this documented?
  • what will be catched by this handler? Will it catch django.http.Http404, django.http.HttpResponseNotFound, django.http.HttpResponse (with status=404)?

Answer

Shang Wang picture Shang Wang · Feb 2, 2016

As we discussed, your setup is correct, but in settings.py you should make DEBUG=False. It's more of a production feature and won't work in development environment(unless you have DEBUG=False in dev machine of course).