[Django]-How to handle database exceptions in Django?


Database Exceptions are documented,
check this answer to see an example of how to use them.

If you are encountering this error while processing a form you should probably handle the exception when validating your form. So in case an exception is raised you redisplay the form with the appropriate error message.



In Django documentation, these exceptions below are introduced as database exceptions and in PEP 249, what causes these exceptions below are explained. For example, OperationalError is caused by lost update and write skew conditions, statement timeout, unexpected disconnection and so on:

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

In my opinion, using DatabaseError should be the easiest way to handle all database exceptions.

The below is the example of the view test with DatabaseError:

# "views.py"

from .models import Person
from django.db import transaction, DatabaseError
from django.http import HttpResponse

def test(request):
        obj = Person.objects.get(id=2)
        obj.name = "David"
    except DatabaseError as e:
        return HttpResponse(e)

    return HttpResponse("Success")

Leave a comment