views:

140

answers:

2

Apparently, the way Django flatpages works is that it handles the 404 thrown by other apps. I was wondering if I could do another flatpages-type app that gets a crack at the 404 before flatpages does. I tried this without success so far. A template gets rendered but the data doesn't come through.

Is it even possible?

+2  A: 

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  A: 

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.

Justin Voss
Thanks for the suggestion. That's interesting about middleware order. I tried reversing the order, but it didn't make a difference in my case.
rick