class FlatpageFallbackMiddleware
Each time any Django application raises a 404 error, this middleware checks the flatpages database for the requested URL as a last resort. Specifically, it checks for a flatpage with the given URL with a site ID that corresponds to the SITE_ID
setting.
If it finds a match, it follows this algorithm:
- If the flatpage has a custom template, it loads that template. Otherwise, it loads the template
flatpages/default.html
. - It passes that template a single context variable,
flatpage
, which is the flatpage object. It usesRequestContext
in rendering the template.
The middleware will only add a trailing slash and redirect (by looking at the APPEND_SLASH
setting) if the resulting URL refers to a valid flatpage. Redirects are permanent (301 status code).
If it doesn’t find a match, the request continues to be processed as usual.
The middleware only gets activated for 404s – not for 500s or responses of any other status code.
Flatpages will not apply view middleware
Because the FlatpageFallbackMiddleware
is applied only after URL resolution has failed and produced a 404, the response it returns will not apply any view middleware methods. Only requests which are successfully routed to a view via normal URL resolution apply view middleware.
Note that the order of MIDDLEWARE
matters. Generally, you can put FlatpageFallbackMiddleware
at the end of the list. This means it will run first when processing the response, and ensures that any other response-processing middlewares see the real flatpage response rather than the 404.
For more on middleware, read the middleware docs.
Ensure that your 404 template works
Note that the FlatpageFallbackMiddleware
only steps in once another view has successfully produced a 404 response. If another view or middleware class attempts to produce a 404 but ends up raising an exception instead, the response will become an HTTP 500 (“Internal Server Error”) and the FlatpageFallbackMiddleware
will not attempt to serve a flat page.
Please login to continue.