Open In App

Exception Handing in Django

Last Updated : 19 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will explore exception handling in Django, examining its significance and learning how to effectively manage exceptions. Through a practical example, we will illustrate the concept and subsequently delve into the solutions for handling exceptions.

Exception Handing in Django

Here, we are explaining exceptions handing in Django in the below points.

  • What is an Exception in Django?
  • URL Resolver Exceptions in Django
  • Database Exceptions in Django
  • What is Exception Handing in Django?
  • How to Perform Exception Handling in Django

What is an Exception in Django?

In Django, exceptions are used to handle errors and exceptional situations that may arise during the execution of a web application. Django provides a set of built-in exception classes that developers can use to catch and handle specific types of errors. Below is a table that provides an overview of some common Django exception classes along with their descriptions:

Exception Classes in Django

Exception Class

Description

django.core.exceptions.ObjectDoesNotExist

Raised when attempting to access an object that doesn’t exist in the database.

django.core.exceptions.ValidationError

Used to collect validation error messages from forms.

django.core.exceptions.ImproperlyConfigured

Raised when the Django project or application is not configured correctly

django.db.utils.IntegrityError

Raised when a database integrity constraint is violated.

django.core.exceptions.MultipleObjectsReturned

Raised when multiple objects are returned but only one was expected.

django.http.Http404

Raised to indicate that the requested resource could not be found.

URL Resolver Exceptions in Django

There are two type of URL Resolver Exception in Django

  1. Resolver404 : In Django, the Resolver404 It is raised when Django’s URL resolver cannot find a match for the requested URL. It typically occurs when a URL pattern is not defined, and Django cannot determine which view or resource to dispatch the request to
  2. NoReverseMatch : In Django, the NoReverseMatch exception is raised when the URL resolution process encounters an issue and cannot find a matching URL pattern for a given set of arguments.

Database Exceptions in Django

There are three type of Database Exceptions in Django

  1. DatabaseError: DatabaseError in Django represents a generic database-related error. It serves as a base class for more specific database-related exceptions, capturing issues that can arise during database operations.
  2. IntegrityError:IntegrityError is raised when there is a violation of the database integrity constraints, such as unique constraints. For example, attempting to insert a duplicate key into a unique field could trigger this exception.
  3. DataError:DataError indicates issues with the data being processed, such as incorrect data types or values that don’t conform to the expected format. It may occur when there’s a mismatch between the type of data being provided and the expected data type in the database schema.

What is Exception Handing in Django?

Exception handling in Django refers to the process of managing and responding to errors or exceptional situations that may occur during the execution of a Django application. In a web framework like Django, various errors can arise, such as database connection issues, missing files, or unexpected input. Exception handling allows developers to anticipate and gracefully address these situations, preventing the application from crashing and providing a more user-friendly experience.

How to Perform Exception Handling in Django

Django provides mechanisms to catch and handle exceptions, enabling developers to implement custom error pages, log errors for debugging, and take appropriate actions to maintain the stability and reliability of the application.

To install Django follow these steps.

Starting the Project Folder

To start the project and appn use this command

django-admin startproject core
cd core
python manage.py startapp home

Now add this app to the ‘settings.py’

INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"home",
]

File Structure :

sjdngg

Setting Necessary Files

views.py : This Django code uses the `render` function to display the “home.html” template when the `home` view is accessed.

Python3




from django.shortcuts import render
 
def home(request):
    return render(request, "home.html")


urls.py: This Django code configures URL patterns for the application. It includes paths for the admin interface and the home page, utilizing the `home` view from the `home` app’s views. The empty path (”) directs to the home view, identified by the name “home.”

Python3




from django.contrib import admin
from django.urls import path
from home.views import *
 
urlpatterns = [
    path("admin/", admin.site.urls),
    path('', home, name="home"),
     
]


Creating User Interface

templates/home.html : This HTML code defines a basic document structure with a green-colored “GeeksforGeeks” heading. It includes standard meta tags for character set and viewport settings.

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
</body>
</html>


Handle Missing/Not exist Page

To handle exception handling in Django, make the following changes and create a file named “404.html” to manage missing and non-existent pages.

settings.py : In Django, `DEBUG = False` signifies production mode, and `ALLOWED_HOSTS = [“*”]` permits requests from any host.

DEBUG = False
ALLOWED_HOSTS = ["*"]



views.py : This Django code defines a `home` view rendering “home.html” and an `error_404_view` to handle 404 errors by rendering a custom “404.html” page.

Python3




from django.shortcuts import render
 
def home(request):
    return render(request, "home.html")
   
def error_404_view(request, exception):
    return render(request, '404.html')


urls.py : This Django code configures URL patterns, directing paths to the admin interface and the home view. It also sets up a custom 404 error handler, pointing to the `error_404_view` in the `home.views` module.

Python3




from django.contrib import admin
from django.urls import path
from home.views import *
 
urlpatterns = [
    path("admin/", admin.site.urls),
    path('', home, name="home"),  
]
handler404 = 'home.views.error_404_view'


templates/404.html : This HTML code defines a custom 404 error page with a message indicating that the page doesn’t exist or is missing. It includes a link to redirect users to the home page using the Django `{% url ‘home’ %}` template tag.

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>404 Error Page</h1>
    <h3>Sorry, This Page Doesn't Exist or Missing.</h3>
    <a href="{% url 'home' %}">Go To Our Home Page</a>
     
</body>
</html>


Output:

Conclusion

In conclusion, exception handling in Django is crucial for robust and user-friendly web applications. By anticipating and gracefully addressing errors, developers can ensure the stability and reliability of their applications. Django provides mechanisms such as custom error views, allowing for tailored responses to different types of exceptions. Properly configuring error handling settings, creating custom error pages, and implementing custom views for specific error cases contribute to a smoother user experience and aid in debugging during production.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads