Showing 404 errors In Django

Visit a category page which doesn’t exist for example, You should see DoesNotExist exception like this:

As there is no such category in the database the URL 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 or 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 and modify the post_detail() view as follows:


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, 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 file and amend post_detail() view as follows:


Save the file and visit, 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.


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 file and update post_by_category() and post_by_tag() view functions to use get_list_or_404() method as follows:


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

Let’s implement this URL pattern.

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


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


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


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 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 in the blog app and update post_list(), post_by_category() and post_by_tag() views as follows:


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.

1 thought on “Showing 404 errors In Django

  1. Got below error , please suggest

    Page not found (404)
    Request Method: GET
    Request URL:
    Using the URLconf defined in django_project.urls, Django tried these URL patterns, in this order:

    ^category/(?P[\w-]+)/$ [name=’post_by_category’]
    ^tag/(?P[\w-]+)/$ [name=’post_by_tag’]
    ^(?P\d+)/(?P[\w\d-]+)$ [name=’post_detail’]
    ^$ [name=’post_list’]
    The current path, 3/the-great-djnago-blog/, didn’t match any of these.

    You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

Leave a Comment

%d bloggers like this: