Updated May 20, 2023
Introduction to Django Exceptions
A program deviates from its normal execution and enters an abnormal state when an event causes an exception. The try and exception blocks in the exception strategy help handle these exceptions. These Python-oriented exceptions are widely classified deep. From a django perspective, the django framework holds its own set of exceptions. The Django framework has designed exceptions to handle various scenarios that may arise within it. Here is a brief list of these exceptions and when they may occur.
Standard Django Exceptions List
The Django setup may trigger the following standard exceptions.
AppRegistryNotReady: There are two instances where this error could be triggered. First is when there is an attempt to use the models associated with the django setup before the app is successfully loaded. The second is placing an invalid app in the INSTALLED_APPS directory. So placing an application that cannot be successfully imported will also throw this error. This error is related to the INSTALLED APPS section in the settings.py file.
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'
}
}
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.postgres',
'Django_app1'
]
- ObjectDoesNotExist: If the corresponding model does not include an object, it will trigger an error called “objectDoesNotExist.” This exception is a base class of the DoesNotExist exceptions.
- FieldDoesNotExist: If the django framework does not include a certain field in the database or model being used, it will display a FieldDoesNotExist error. The model’s _meta.get_field() triggers this error when the field being searched for is invalid for that model or its parents and is not present in the models.py file.
- MultipleObjectsReturned: The Django framework generates an exception called “Multiple Objects” when it returns multiple objects instead of a single object as programmed in a query. This exception occurs due to discrepancies in the number of objects the query returns. The subclassed version of the core exceptions class is held by every model class, which assists in determining the object type when multiple objects are returned.
- SuspiciousOperation: The django framework labels suspicious operations as exceptions under the category of suspicious operations. We identify security-related exceptions as particularly suspect. The framework further classifies these suspicious operation exceptions into subcategories listed below.
- DisallowedHost
- DisallowedModelAdminLookup
- DisallowedModelAdminToField
- DisallowedRedirect
- InvalidSessionKey
- RequestDataTooBig
- SuspiciousFileOperation
- SuspiciousMultipartForm
- SuspiciousSession
- TooManyFieldsSent
- PermissionDenied: The permission denied exception is raised when the user does not hold suitable access or authority for the attempted entity. This is an access-oriented exception. In most instances, security-oriented issues will be tagged under this exception and triggered as permission-denied instances. This exception offers additional integrity in stabilizing the application.
- ViewDoesNotExist: The url.py file often causes the ViewDoesNotExist error. This error indicates that the views.py file cannot find the view specified in urls.py. Certain conditions may also cause this error to occur.
Example:
from django.shortcuts import render
from django.http import HttpResponse
from Django_app1.forms import Valueform
from django.core.exceptions import ViewDoesNotExist
from django.contrib.auth.models import User
def template_view(request_iter):
template_Var = {
"Entity_name": "Educba",
"Entity_type" : "tutorial",
"Entity_students_count": 345,
"Error_Message": "No Valid Entity found"
}
return render(request_iter,'design.html',context=template_Var)
def formView(request_iter):
form = Valueform()
if request_iter.method == "POST":
value = Valueform(request_iter.POST)
if value.is_valid():
first_name = value.cleaned_data['first_name']
if request_iter.session.has_key(first_name):
print(request_iter.session.items())
return render(request_iter, 'Session.html' )
else:
request_iter.session[first_name] = first_name
return render(request_iter, 'Form_Handeling.html', {"form":form})
else:
raise ViewDoesNotExist("!!! INVALID VIEW !!!")
return render(request_iter, 'Form_Handeling.html', {"form":form})
- ImproperlyConfigured: If the database setup of the Django framework is incorrect, it may cause connectivity issues that result in an exception. The exception is related to improper configuration.
Example:
Base.py (Source code from which the exception is raised):
def databases(self):
if self._databases is None:
self._databases = settings.DATABASES
if self._databases == {}:
self._databases = {
DEFAULT_DB_ALIAS: {
'ENGINE': 'django.db.backends.dummy',
},
}
if DEFAULT_DB_ALIAS not in self._databases:
raise ImproperlyConfigured("You must define a '%s' database." % DEFAULT_DB_ALIAS)
if self._databases[DEFAULT_DB_ALIAS] == {}:
self._databases[DEFAULT_DB_ALIAS]['ENGINE'] = 'django.db.backends.dummy'
return self._databases
Base.py (Framework source code which triggers the exception):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
Snap of the Exception:
- MiddlewareNotUsed: A problem arises when the middleware setup for the django project has issues. The project may have a misconfigured middleware in its SETTINGS.py file. If there are problems with the middleware configurations, they will manifest as a middleware configuration issue.
SETTINGS.py (Middleware configurations):
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
- FieldError: Django’s Field Error Exception classification tackles issues that may arise with fields in databases containing multiple fields, such as invalid or problematic retrieval.
- ValidationError: Ensuring consistency and accuracy in entering information into a field is of utmost importance. Custom or default validation methods can help identify errors that may arise. The validation process reports any issues detected as a Validation Error exception.
Recommended Articles
We hope that this EDUCBA information on “Django Exceptions” was beneficial to you. You can view EDUCBA’s recommended articles for more information.