How to return 404 error in Django

If you are developing a web application, then most probably you will come across situations where you need to show the 404 (not found) page. We will talk about this in this article.

When you should return 404

It is a good practice to use a 404 page in cases when users are accessing the wrong URLs, for instance, when the link you used to access the page is broken. We will also talk about how to use the right status code for this situation. You should return 404 HTTP error if one of the following is true:

  • The page does not exist.
  • The requested page was deleted.
  • Page not found.

Django — return 404

Python Django provides a number of functions to customize the 404 page. Using them you can easily configure your 404 page without having to write a new view function. Let’s have a look at how to return a 404 error in Django.

First, import Http404 from django.http module. Next, raise the Http404 exception within your view. For example, here is views.py file for the view which always returns 404:

from django.http import Http404

def not_found(req):
    raise Http404

Remember to route the not_found view. To do it, write the following to urls.py:

from . import views
from django.urls import path

urlpatterns = [
    # ...your other routes...
    path('nowhere/', views.not_found), # for 404 demo
]

You should not do this in production apps. We do it now just for the sake of demonstration. Now, restart your application. If you go to the routed URL /nowhere/, you will see one of the following:

  • If you have DEBUG=True set in settings.py you will see Django app traceback.
  • Otherwise, you will see the 404 error template you specified in settings.py or templates/404.html

Using get_object_or_404 function

Sometimes you need to retrieve a model from a database and return 404 error if the model does not exist. Of course, you can use an if-else statement, but you can use a shortcut, get_object_or_404 function. See the code example below:

from django.shortcuts import get_object_or_404, render

# example model - use models.py to create one
from app.models import Page

def get_page(req, page_id):
    page = get_object_or_404(Page, id=page_id)
    return render(req, 'app/page.html', { 'text': page.text })

We used an imaginary template ‘app/page.html’, which renders the text variable we passed. If the Page model with id page_id does not exists, Django will return the 404 not found error.

Conclusion

To return 404 in Django Framework, you should include the Http404 exception and raise it within a view function. Also you can use get_object_or_404 function from django.shortcuts if you retrieve a model from a database in your view. You learned how to return 404 error and get it handled correctly.

Leave a Comment