- What is Python?
- How to Install Python?
- Python Variables and Operators
- Python Loops
- Python Functions
- Python Files
- Python Errors and Exceptions
- Python Packages
- Python Classes and Objects
- Python Strings
- PostgreSQL Data Types
- Python Generators and Decorators
- Python Dictionary
- Python Date and Time
- Python List and Tuples
- Python Multithreading and Synchronization
- Python Modules
- What is Python bytecode?
- Python Regular Expressions
Python Panda Tutorial
- Python Pandas Tutorial
- Python Pandas Features
- Advantages and Disadvantages of Python Pandas
- Pandas Library In Python
- Pandas Series To Frame
- Python Dataframeaggregate and Assign
- Pandas Dataframe Describe
- Pandas Dataframe Mean
- Pandas Hist
- Pandas Dataframe Sum
- How to convert Pandas DataFrame to Numpy array
- Pandas Concatenation
- Pandas Shift
- Pandas Rolling
- Data Analysis With Pandas and Python
- How Python Panda Are Helpful For With Data Science
- Selenium Basics
- Selenium with Python Introduction and Installation
- Navigating links using get method Selenium Python
- Locating Single Elements in Selenium Python
- Locating Multiple elements in Selenium Python
Python Flask Tutorial
- How to Install Django and Set Up a Virtual Environment in 6 Steps
- Django MTV Architecture
- Django Models
- Django Views
- Django Templates
- Django Template Language
- Django Project Layout
- Django Admin Interface
- Django Database
- Django URLs and URLConf
- Django Redirects
- Django Cookies and Cookies Handling
- Django Caching
- Types of Caching in Django
- Django Sessions
- Django Forms Handling & Validation
- Django Exceptions & Error-handling
- Django Forms Validation
- Django Redirects
- Django Admin Interface
- Django Bootstrap
- Ajax in Django
- Django Migrations and Database Connectivity
- Django Web Hosting and IDE
- Django Admin Customization
- What is CRUD?
- Django ORM
- Django Request-Response Cycle
- Django ORM
- Making a basic_api with DRF
- Django Logging
- Django Applications
- Difference between Flask vs Django
- Difference between Django vs PHP
- Numpy Introduction
- NumPy– Environment Setup
- NumPy - Data Types
- NumPy Histogram
- Matrix in NumPy
- NumPy Arrays
- NumPy Array Functions
- Matrix Multiplication in NumPy
- NumPy Matrix Transpose
- NumPy Array Append
- NumPy empty array
- NumPy Linear Algebra
- NumPy sum
- NumPy Normal Distribution
- NumPy correlation
- Why we learn and use Numpy?
- Introduction To Tensorflow
- INTRODUCTION TO DEEP LEARNING
- EXPLAIN NEURAL NETWORK?
- CONVOLUTIONAL AND RECURRENT NEURAL NETWORK
- INTRODUCTION TO TENSORFLOW
- INSTALLATION OF TENSORFLOW
- TENSORBOARD VISUALIZATION
- Linear regression in tensorflow
- Word Embedding
- Difference between CNN And RNN
- Explain Keras
- Program elements in tensorflow
- Recurrent Neural Network
- Tensorflow Object Detection
- EXPLAIN MULTILAYER PERCEPTRON
- GRADIENT DESCENT OPTIMIZATION
Interview Questions & Answers
Django Exceptions & Error-handling
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
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.
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.
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 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.
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.
- 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.
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.
There can be validation errors which do not belong to any particular field in Django. They are NON_FIELD_ERRORS.
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:
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.
It is a common occurrence. When we request for a URL which is not defined in our urls-config, we get this error.
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:
- Database is not found
- Interface is not there
- Database is not connected
- Input data is not valid etc.
We raise these errors when:
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.
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.
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.
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.
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.