Django Exception Handling – A Brief How-To

Django Exception Handling

In this article, we will learn Django exception handling in a very brief and concise manner while covering most of the exceptions and error messages in Django.

Why do we need to handle exceptions?

As a developer, you will encounter various errors either while making the web APIs, templates, or while writing any other piece of code.

Dealing with them is a very time taking process but also is an essential task, and hence this critical skill of exceptions and error handling comes into the picture.

What are Exceptions?

Exceptions in coding are those types of events that lead to undesirable events. These are detected by run-time executives(like consoles and terminals) or by Operating Systems.

They need not necessarily stop the whole program but will lead to undesirable outputs.

For e.g :

Let’s say the client wants to see a particular object from the database. But for some reason, that specific object is not present there.

In this case, the server won’t come to a halt, but the client will get an error since the object is not present in the DB, which is undesirable.

The key difference between Exceptions and Errors

Errors are those events due to which the whole system will come to a halt, and the program will not execute.

Nothing can be done with errors; we can only detect and then make appropriate changes such that they don’t happen.

On the other hand, exceptions are something that the developers can deal with without letting the system come to a halt.

Types of Django Exceptions

Exception Handling
Exception Handling

There are many kinds of exceptions in Django, out of which five are extremely important and are used most frequently.

  • Django Exception classes
  • Django URL Resolver Exceptions
  • Django Database Exceptions
  • Django Http Exceptions
  • Django Transaction Exceptions

We will learn about them in detail.

1) Django Exception classes

IDExceptionDescription
1AppRegistryNotReady– It occurs when the Django models are loaded before the Django app itself.
– This exception occurs when you are writing your own scripts and not with default Django app files.
2ObjectDoesNotExistAs the name suggests, occurs when Object does not exist.
3EmptyResultSetOccurs when a query returns an empty set
4FieldDoesNotExistThis occurs when Field doest not exist in a model.
5MultipleObjectsReturnedThis occurs when a query returns more than one result
6SuspiciousOperationThis happens when the client does something suspicious for security reasons
7PermissionDeniedOccurs when the user tries to perform a task which he is not allowed to
8ViewDoesNotExistOccurs when Views doesnt not exist
9MiddlewareNotUsedThis occurs when particular middleware is not used in the MIDDLEWARE section of settings.py
10ImproperlyConfiguredThis occurs when somehow, Django is improperly configured. Usually doesn’t happen when working with default Django Files.
11FieldErrorHappens when there is an error in Model field
12ValidationErrorHappens when Data validation fails in forms or model forms.
Django Exception classes

2) Django URL Resolver Exceptions

IDExceptionDescription
1Resolver404– Raised by the function resolve(), a part of Django.http.Http404 library.
– The exception occurs when path() does not have a valid View to map.
2NoReverseMatchThis occurs when the user searches a wrong endpoint.
Django URL Resolver Exceptions

3) Django Database Exceptions

IDExceptionDescription
1DatabaseErrorOccurs when DB is not available
2IntegrityError– This occurs when DB expects a value for a field but doesn’t get it from the user.
– If True, Django will store empty values as NULL in the database. Default is False.
3DataErrorOccurs due to data-related issues
Django Database Exceptions

4) Django Http Exceptions

This we have seen many times. These are the HTTP exceptions that we import from django.http library

IDExceptionDescription
1UnreadablePostErrorOccurs when a user cancels an upload.
Django Http Exceptions

5) Django Transaction Exceptions

IDExceptionDescription
1TransactionManagementErrorThis is raised for all the problems that occur due to database transactions
Django Transaction Exceptions

Simple Implementation of Exception Handling in the Django app

We will do a simple DoesNotExist exception handling on an application that shows information about a particular item in the server.

The code is a part of the Web Application itemsapp built in the REST API article.

Itemsapp is a simple REST API application that allows clients to

  1. View a list of items present in the server (GET endpoint: hostwebsite/items)
  2. Add a new item into the DB (POST endpoint: hostwebsite/items)
  3. View a particular item (GET endpoint: hostwebsite/item/<id>)
  4. Edit a particular item (PUT endpoint: hostwebsite/item/<id>)
  5. Delete a particular item (DELETE endpoint: hostwebsite/item/<id>)

To learn how to make the complete web application, do checkout Rest API article.

Now we will create a webpage that shows the information about a particular item from the DB

  • Create a ItemModel in models.py to store information about items:
from django.db import models

# Create your models here.

class ItemsModel(models.Model):
    id = models.IntegerField(primary_key = True)
    name = models.CharField(max_length = 80)
    price = models.IntegerField()

    class Meta:
        ordering = ['name']

    def __str__(self):
        return f"{self.name}:{self.price}"
  • As shown above, the URL path in urls.py will be:
path('/item/<int:nm>',Item)

Now just add a few items into the DB through the admin site.

Admin
Admin
  • Now in views.py, the code to show a particular item with an id = nm will be:
def Item(request,nm):
        item = ItemModel.objects.get(id = nm)
        return HttpResponse(item)

Run the server and check for an object not present in DB, say id = 4

You will get an error message

DoesNotExist
DoesNotExist

Now we will use Django Exception Handling to handle this error. Edit the code in views.py as follows:

def Item(request,nm):
        try:
            item = ItemsModel.objects.get(id = nm)
        except ItemsModel.DoesNotExist:
            return HttpResponse('Exception: Data Not Found')
        return HttpResponse(item)

Notice the line “except ItemsModel.DoesNotExist“. This is where Python automatically captures the exception. You can replace the exception with one of the exceptions from the list above, and handle the same with a custom error message.

For that first import

from django.core.exceptions import *

That’s it, now we can go on and add exception we want

def Item(request,nm):
        try:
            item = ItemsModel.objects.get(id = nm)
        except ObjectDoesNotExist:
            print('Data Not Found')
        return HttpResponse(item)

Now run the server and search for id = 4

Exception Handling
Exception Handling

Similarly, we will handle other important and most used exceptions from the django.core.exceptions

Some other important Exceptions

First we will have to import the library

from django.core.exceptions import <error_name>

Lets go through the important exceptions

Field Dos Not Exist

This happens when the model field does not exist

try:
    Model.objects.get(<field> = '<value>')
except FieldDoesNotExist:
    print('The Field is missing')

Multiple Objects Returned

Happens when more than one object in DB has same value for a certain field

try:
    Model.objects.get(<name> = '<value>')
except MultipleObjectsReturned:
    print('More than one object with the same name are present in the Database')

View Does Not Exist

Happens when we call a view through path() in urls.py , but the view does not exist.

try:
    path('item/', <View>)
except ViewDoesNotExist:
    print('The View does not exist in views.py')

Validation Error

Happens when certain information in the form data is not valid

data = form.cleaned_data['name']
if '<field_name>' not in data:
    raise ValidationError('This name does not exist')

Conclusion

That’s it, fellas! I do hope that this article helped increase your knowledge and understanding of Django exceptions. Do refer to the official documentation for more information.

Stay safe !! keep Learning !!