Django Exceptions & Error-handling made Easy with this Handy Guide!

As a developer, we are always dealing with errors. There are tons of errors in our applications, websites, and programs. I am no exception to that. Even my first APIs had errors when I started learning. It took a decent amount of time to learn error handling.

Error handling is an important skill. It is a must for all developers. We have implemented it in our Django forms DataFlair tutorial. There we validated the form data and it was to check for any error in user-input.

Errors and exceptions although used synonymously, are different. Let’s learn more about them.

Prerequisite to Django Exceptions

Knowledge of Python is a must at this point. You should have some experience with exception handling in python.

Take a deep dive into Python programming for learning exception handling and various other concepts with our 240+ Python Tutorials

What are Exceptions?

Exceptions are those events in a program occurring of which can lead to undesirable behavior. They are detectable by run time executive or Operating System. Exceptions do not always emerge from errors.

Errors, on the other hand, are complete halt. If an error occurs, your program will not execute. When the errors like OutOfMemory occurs, your program literally has no memory to execute. Thus, the execution stops.

The programmers can do nothing about errors. Errors can only be caught and an appropriate response can be generated, that’s all can be done.

Exceptions are the ones in which we developers actually deal with.

We all are familiar with web errors, the most popular being 404 FileNotFound Error. Let’s learn how Django raises the different kinds of exceptions.

Django Exceptions

There are multiple packages for developer’s use. These packages may/ may not come in your use-case. For the matter, the 1st package we are going to discuss is for those developers who are writing their own Python scripts. These developers customize the Django at a low level.

Django Exceptions and Error Handling

1. django.core.exceptions Package

This package provides us with low-level exceptions. It enables us to define new rules for our Django project. We can load models, views in our own defined ways.

This module has use-cases like:

  • When you are working on a custom middleware.
  • When making some changes to Django ORM.

For that, we will have to understand some very basic concepts.

In the screenshot below, we can see the list of exceptions provided by this package.

List of exceptions - Django.core.exceptions

1.1. AppRegistryNotReady

This error occurs when the application model is imported before the app-loading process.

When we start our Django server, it first looks for settings.py file.

Django then installs all the applications in the list INSTALLED_APPS. Here, is a part of that process.

App registry in brief:

When Django project starts, it generates an application registry. It contains the information in settings.py and some more custom settings. This registry will keep record and install all the important components.

This registry contains settings-config of all apps inside INSTALLED_APPS. It is the first kernel of your Django project. To use any app or submodule in your project, it has to load-in here first.

It is useful in exception catching when developing your own scripts. It may not occur when using default Django files.

1.2. ObjectDoesNotExist

This exception occurs when we request an object which does not exist. It is the base class for all the DoesNotExist Errors.

ObjectDoesNotExist emerges mainly from get() in Django.

Brief on get():

get() is an important method used to return data from the server. This method returns the object when found. It searches the object on the basis of arguments passed in the get(). If the get() does not find any object, it raises this error.

1.3. EmptyResultSet

This error is rare in Django. When we generate a query for objects and if the query doesn’t return any results, it raises this error.

The error is rare because most of the queries return something. It can be a false flag, but for custom lookups this exception is useful.

1.4. FieldDoesNotExist

This one is clear from its name. When a requested field does not exist in a model, this meta.get_field() method raises this exception.

Meta.get_field() method mediates between views and models. When the model objects are in view functions, Django uses this method for searching the fields. This method looks for the requested field in super_models as well. It comes in handy when we have made some changes to models.

1.5. MultipleObjectsReturned

When we expect a query to return a single response/ object but it returns more than one object, then Django raises this exception.

The MultipleObjectsReturned is also an attribute of models. It is necessary for some models to return multiple objects but for others, it cannot be more than one. This exception helps us to get more control over model data.

1.6. SuspiciousOperation

It is one of the security classes of Django. Django raises this error when it has detected any malicious activity from the user. This exception has many subclasses which are helpful in taking better security measures.

When anyone modifies the session_data, Django raises this exception. Even when there is a modification in csrf_token, we get this exception.

There are many subclasses, dealing with very particular problems. These subclasses are:

  • DisallowedHost
  • DisallowedModelAdminLookup
  • DisallowedModelAdminToField
  • DisallowedRedirect
  • InvalidSessionKey
  • RequestDataTooBig
  • SuspiciousFileOperation
  • SuspiciousMultipartForm
  • SuspiciousSession
  • TooManyFieldsSent

As we can see, all of them are very particular in some kind of data defect. These exceptions can detect various types of activities on the server. They have helped a lot of developers to build reliable and secure applications.

1.7. PermissionDenied

This exception is the clearest of all. You must have dealt with this exception while working on static files. Django raises this error when we store our static files in a directory which is not accessible.

You can raise this using the try/ except block but it will be more fun, the static files way. To raise it, change static folder settings to hidden or protected.

Join DataFlair on Telegram

1.8. ViewDoesNotExist

We all have experienced this one. Websites have a very evolving frontend design and there are frequent modifications which can lead to some faulty urls.

Django checks for all urls and view function by default. If there is something wrong, the server will show an error.

But we can also raise this error when urls-config can’t get the view to load. It is a problem which occurs while using relative URL addressing.

You can implement this from Django Static Files Tutorial.

1.9. MiddlewareNotUsed

Django is very useful at times. It raises this exception when an unused middleware is present in MIDDLEWARES list. It’s like the caching middleware. Whenever we have not implemented caching on our website, it will throw this exception.

All the middlewares present in our settings.py are utilized. Most of them are there for the admin app. You can see in the below image that Django comes with pre-installed middlewares that we may require in our application.

django middleware exception

This is the snapshot of our recent application.

You can explore more about this exception from Django Caching Tutorial.

1.10. ImproperlyConfigured

You must have encountered this exception when configuring your first project. This exception is for the main settings.py file. If there are some incorrect settings in the main settings then this error will raise. It can also come up if the middlewares or modules do not load properly.

It is pretty helpful, as it saves us a lot of bugs.

1.11. FieldError

We raise field errors when models have some errors. For example: using the same name in a class is correct syntactically but it can be a problem for Django Models. Therefore, the exceptions will check for these kinds of things.

Cases like:

  • Fields in a model defined with the same name
  • Infinite loops caused by wrong ordering
  • Invalid use of join, drop methods
  • Fields name may not exist, etc.

1.12. ValidationError

We used the validation error in validating the form data. This class is a sub-class of django.core.exceptions class. It is extensively used to check data correctness. It will match the data with the model field or forms field. And, it ensures that no security threat is there due to illegal characters in user-input.

You can understand more about them in our Django Forms article.

There can be validation errors which do not belong to any particular field in Django. They are NON_FIELD_ERRORS.

2. URL Resolver Exceptions

This class is a major part of urls.py for defining urls. We import our path function from urls class.

django.urls is one of the core classes of Django without which it might not function. This class also provides some exceptions:

2.1. Resolver404

We raise this exception if the path() doesn’t have a valid view to map. The Resolver404 shows us the error page. It is django.http.Http404 module’s subclass.

2.2. NoReverseMatch

It is a common occurrence. When we request for a URL which is not defined in our urls-config, we get this error. We all have seen that one page.

reversematchnotfound error

This exception is also raised by django.urls module. It applies to regular expressions as well.

3. Database Exceptions

We can import these exceptions from django.db module. The idea behind this implementation is:

Django wraps the standard database exceptions. And, when it happens, our Python code can correspond with the database exception. That makes it easy to deal with database exceptions in Python at a certain level.

The exception wrappers provided by Django work in the same way as Python database API.

The errors are:

  • InterfaceError
  • DatabaseError
  • DataError
  • IntegrityError
  • InternalError
  • ProgrammingError
  • NotSupportedError

We raise these errors when:

  • Database is not found
  • Interface is not there
  • Database is not connected
  • Input data is not valid etc.

4. Http Exceptions

We used this class in our first views. The HttpResponse is a sub-class of django.http class. The module provides some exceptions and special responses.

UnreadablePostError

This exception occurs when a user uploads a corrupt file or cancels an upload. In both cases, the file received by the server becomes unusable.

5. Transaction Exceptions

A transaction is a set of database queries. It contains the smallest queries or atomic queries. When an error occurs at this atomic level, we resolve them by the django.db.transaction module.

There are errors like TransactionManagementError for all transaction-related problems with the database.

6. Testing Framework Exceptions

The django.test package also comes with many exceptions. We have also raised one exception from this class in our Django Redirect Tutorial

It is the infinite loop that we created with redirects. Check out that article’s last part.

7. Python Exceptions

Django is a Python framework. Of course, we get all the pre-defined exceptions of Python as well. Python has a very extensive library of exceptions. And, you can also add more modules according to use-case.

Don’t forget to check out the Python Exceptions Tutorial for more information.

Summary

In this article, we defined many exceptions. They are mainly for developers who want to customize Django’s inside-out, the exceptions in django.core package is just that. But, before working on exceptions, you will need to understand Django’s functions and methods.

Any queries or feedbacks? Enter in the comment section. We will be glad to hear from you.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.