Users Online

· Guests Online: 35

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Articles Hierarchy

Django Tutorial

Django Exceptions

Django Exceptions

Introduction to Django Exceptions

An exception can be defined as an event that will be deviating the normal execution of a program into an abnormal state. The try and exception blocks in the exception strategy are helpful in handling these exceptions. These python oriented exceptions are widely classified deep. From a django perspective, the django framework holds its own set of exceptions. All these exceptions which are tagged under django framework are considered to be created to be suitable to address the various possible exception scenarios which are generated in django framework. These classified set of django exceptions are mentioned below briefly along with their possible instance of occurrence.

Standard Django Exceptions List

Below are the list of overall standard exceptions which are been triggered in Django setup,

AppRegistryNotReady: There are two instances were this error could be triggered, First is when there is an attempt to use the models associated to django set up before the app is been successfully loaded. 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 more 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: When an object is not a part of the corresponding model then the error objectDoesNotExit gets triggered. This exception is a base class of the DoesNotExist exceptions.
  • FieldDoesNotExist: The field does not exist an error is triggered when the attempted field is not a part of the database or the model referred. this means when the attempted field in the query triggered is not a part of the model produced in the models.py file then the FieldDoesNotExist error will be triggered by the django framework. This error is raised by the _meta.get_field() of a model when the attempted field is not a valid part of that model or the parents of the model.
  • MultipleObjectsReturned: This exception is raised when there is a discrepancy on a number of objects being returned back by the query. So when querying the database if the query expects a response of one object to be returned but on execution case, if more than one object is delivered as output for the query then the multiple objects exception will be triggered by the django framework. The base version for this exception is inherited in the core. exceptions class, Basically every model class will be holding a subclassed version which will be helpful in determining the object type for which multiple objects are been returned.
  • SuspiciousOperation: All identified operation which are considered to be suspicious by django framework will be tagged under the exception of the suspicious operation. More predominantly exceptions which fall under security bracket are considered to be suspicious operation exceptions. This suspicious operation exception is subdivided into subclass exceptions as 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. At most instances, security oriented issues will be tagged under this exception and triggered as permission denied instance. This exception offers additional integrity in stabilizing the application.
  • ViewDoesNotExist: This exception is predominantly raised by the url.py file. When an attempted view mentioned in the urls.py file is not present in the actual views.py file then the ViewDoesNotExist error will be raised. This exception could also be raised conditionally.

Example:

Django Exceptions-1.1

Django Exceptions-1.2

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
deftemplate_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)
defformView(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:The improperly configured exception is raised when the database connected to Django is not been configured properly in the django framework. So when there are connectivity issues on the database are then this exception on improper configuration will be triggered.

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:

Django Exceptions-1.3

  • MiddlewareNotUsed:This issue is raised if there is an issue with the middleware setup for the django project. On frequent instance of this issue is when the middleware mentioned is not properly configured in the SETTINGS.py file of the project. When there are valid issues in those middle ware configurations then those will be raised as an 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: With the databases holding a number of fields in it there are possibilities that a field mentioned in a database is not valid or it experiences some kind of issue on its existence or on its retrieval. these classified set of exceptions on the field level are mentioned by the field Error exception in Django.
  • ValidationError: There are a number of ways the data in a field are expected to be validated so that they are needed consistency. These verifications can be achieved by means of custom and default validation entities. So an exception raised from these validations is tagged to be Validation Error exception.

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.72 seconds
10,842,700 unique visits