Showing 404 errors In Django

Visit a category page which doesn’t exist for example, http://127.0.0.1:8000/category/cat_not_exists/. You should see DoesNotExist exception like this:

As there is no such category in the database the URL http://127.0.0.1:8000/blog/category/cat_not_exists/ is completely invalid. In production (i.e when DEBUG=True), instead of throwing a DoesNotExist exception Django will show 500 Internal Server Error.

From the point of view of Search Engine Optimization (SEO), it would be much better to show an HTTP 404 error for the non-existent page instead of showing Internal Server Error or DoesNotExist exception.

The same problem exists in the tag page and the post detail page. Visit any tag or post detail page which doesn’t exist like http://127.0.0.1:8000/tag/tag_not_exists/ or http://127.0.0.1:8000/97712/ and see it yourself.

Showing an HTTP 404 page

Django provides two ways to show 404 error.

  1. HttpResponseNotFound class
  2. Http404 exception

Let’s start with HttpResponseNotFound class.

HttpResponseNotFound class

The HttpResponseNotFound class is an extension of HttpResponse class. It works just like HttpResponse but instead of returning a 200 status code , it returns 404 (which means page not found). To see how it works, open views.py and modify the post_detail() view as follows:

TGDB/django_project/blog/views.py

Here we are wrapping the code which might throw an exception in the try and except block. Now, If get() method throws a DoesNotExist exception then instead of displaying an error page, Django will show a 404 error page with "Page not found" response. Save the changes and visit http://127.0.0.1:8000/99999/, you should get a response like this:

Http404 exception

Another way to show a 404 error page is to raise Http404 exception. Notice that unlike HttpResponseNotFound class, Http404 is an exception. Http404 uses a default 404 page which Django provides. To use it just raise Http404 exception in your code like this:

You can also provide an error message while raising Http404 exception.

Open views.py file and amend post_detail() view as follows:

TGDB/django_project/blog/views.py

Save the file and visit http://127.0.0.1:8000/blog/99999/, you will see the following 404 error page.

We are currently in development mode. In production (i.e when DEBUG=False) Django will show 404 page which looks like this:

The get_object_or_404() method

Most of the time our views function goes like this:

  1. Code try and except block.
  2. Query the database in the try block.
  3. If an exception is thrown, catch the exception in the except block and show a 404 page.

This pattern is so common that Django a provides a shortcurt method called get_object_or_404(). Here is the syntax of get_object_or_404().

Syntax: get_object_or_404(klass, **kwargs)

The klass can be a model, a manager or a Queryset object.

The **kwargs represents all keyword arguments as well as lookup parameters that we have been using with the get() and filter() method.

On success, it returns a single object of the given model, if it can’t find any records then it raises a Http404 exception.

Internally this method calls get() method of objects manager, so you must always use this method to get a single record.

To use get_object_or_404() first import it from django.shortcuts using the following code.

The following examples shows how to use get_object_or_404() method with models, queryset and managers. It also shows that when a matching record is not found, get_object_or_404() raises a Http404 exception.

Example 1: where klass is model

The above code is equivalent to:

Example 2: where klass is queryset

Example 3: where klass is manager

Let’s update our post_detail() view to use get_object_or_404() method.

TGDB/django_project/blog/views.py

The get_list_or_404() method

The get_list_or_404() works just like get_object_or_404() method, but instead of returning a single result, it returns a queryset object. If no matching results found, it raises a Http404 exception.

Open views.py file and update post_by_category() and post_by_tag() view functions to use get_list_or_404() method as follows:

TGDB/django_project/blog/views.py

After updating views, visit any non-existent category page, tag page or post detail page, you should get a proper HTTP 404 error.

Creating SEO friendly URLs

As the situation stands, our post detail page URLs looks like http://127.0.0.1:8000/6/. Although it is working fine, the problem is that by looking at the URL nobody can tell what the post is about. It would be good to create URLs which describes something about the post.

For our blog, we will create a URL pattern like the following:

http://example.com/post-pk/post-slug

Let’s implement this URL pattern.

Open urls.py in the blog app and amend post_detail URL pattern as follows:

TGDB/django_project/blog/urls.py

Update post_detail() view function to accept another parameter called post_slug as follows:

TGDB/django_project/blog/views.py

At last, we need to modify the get_absolute_url() method of the Post model. Open models.py and update get_absolute_url() method of Post model as follows:

TGDB/django_project/blog/models.py

As we are using get_absolute_url() method to generate links to post detail page in our templates, we don’t need to modify anything else. All templates will pick the changes automatically.

To view the updated URL visit http://127.0.0.1:8000/ and click on any post detail page.

Listing posts in reverse chronological order

Currently, all pages of our site display posts in the order in which they are inserted into the database. For usability purpose, it would be much better to display posts in reverse chronological order i.e latest first, oldest last.

This change would be very simple. Open views.py in the blog app and update post_list(), post_by_category() and post_by_tag() views as follows:

TGDB/django_project/blog/views.py

From now on, all the pages of our blog will display posts in reverse chronological order.

Note: To checkout this version of the repository type git checkout 18a.

Leave a Comment