Django’s built-in shortcut get_object_or_404 is a handy way to catch exceptions when a record isn’t found in the database (maybe the user messed with the URL params). But the generic 404 page isn’t always what you want to show. Sometimes it makes a bit more sense to show the user a separate template instead.
To solve this here’s a simple replacement function which makes use of a custom exception and some new middleware.
First the custom exception:
Next the middleware:
Make sure you add the middleware to your settings:
And finally the replacement function:
You can now use this anywhere you were using get_object_or_404:
Using this same design pattern you could easily create a get_object_or_redirect shortcut which redirects the user to another page instead of showing a template.