Django Exceptions

An exception is an abnormal event that leads to program failure. To deal with this situation, Django uses its own exception classes and supports all core Python exceptions as well.

Django core exceptions classes are defined in django.core.exceptions module. This module contains the following classes.

Django Exception Classes

ExceptionDescription
AppRegistryNotReadyIt is raised when attempting to use models before the app loading process.
ObjectDoesNotExistThe base class for DoesNotExist exceptions.
EmptyResultSetIf a query does not return any result, this exception is raised.
FieldDoesNotExistIt raises when the requested field does not exist.
MultipleObjectsReturnedThis exception is raised by a query if only one object is expected, but multiple objects are returned.
SuspiciousOperationThis exception is raised when a user has performed an operation that should be considered suspicious from a security perspective.
PermissionDeniedIt is raised when a user does not have permission to perform the action requested.
ViewDoesNotExistIt is raised by django.urls when a requested view does not exist.
MiddlewareNotUsedIt is raised when a middleware is not used in the server configuration.
ImproperlyConfiguredThe ImproperlyConfigured exception is raised when Django is somehow improperly configured.
FieldErrorIt is raised when there is a problem with a model field.
ValidationErrorIt is raised when data validation fails form or model field validation.

Django URL Resolver Exceptions

These exceptions are defined in django.urls module.

ExceptionDescription
Resolver404This exception raised when the path passed to resolve() function does not map to a view.
NoReverseMatchIt is raised when a matching URL in your URLconf cannot be identified based on the parameters supplied.

Django Database Exceptions

The following exceptions are defined in django.db module.

ExceptionDescription
DatabaseErrorIt occurs when the database is not available.
IntegrityErrorIt occurs when an insertion query executes.
DataErrorIt raises when data related issues come into the database.

Django Http Exceptions

The following exceptions are defined in django.http module.

ExceptionDescription
UnreadablePostErrorIt is raised when a user cancels an upload.

Django Transaction Exceptions

The transaction exceptions are defined in django.db.transaction.

ExceptionDescription
TransactionManagementErrorIt is raised for any and all problems related to database transactions.

Django Exception Example

Suppose, we want to get employee record where id = 12, our view function will look below. It raises a DoesNotExist exception if data not found. This is Django’s built-in exception.

// views.py

def getdata(request):  

    data = Employee.objects.get(id=12)  

    return HttpResponse(data)

// urls.py

path('get',views.getdata)  

It shows the following exception because no record is available at id 12.

Output:

Django Exception example

We can handle it by using try and except, now let’s handle this exception.

// Views.py

def getdata(request):  

    try:  

        data = Employee.objects.get(id=12)  

    except ObjectDoesNotExist:  

        return HttpResponse("Exception: Data not found")  

    return HttpResponse(data);

Output:

Django Exception output

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *