Django get_object_or_404 replacement – get_object_or_template

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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s