[Django]-Can you have more than one app handle a 404 in Django?

3👍

As per the Django docs, you can specify your own view as a 404 or 500 handler:

handler404 = 'mysite.views.my_custom_404_view'

So, your app can define a custom error handling view in views.py that you can setup as the handler for 404 or 500 view in your urls.py

See “Customizing Error views” for more info.

👤vezult

1👍

The way the built-in flatpages app works is with some middleware: the middleware has a function called ‘process_response’ that checks outgoing responses for the 404 status code. If the response is a 404, and the URL matches a flatpage, the middleware suppresses the 404 and returns the rendered flatpage.

You can do the same thing with your own middleware. To make sure that your code is called before the flatpages code, your middleware should come after flatpages in your MIDDLEWARE_CLASSES setting:

# in settings.py
MIDDLEWARE_CLASSES = (
    # ...
    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
    'myapp.middleware.MyMiddlewareClass',
)

The reason it’s after, and not before, is because during the response phase Django applies middleware in reverse order.

Leave a comment