Python django exception handling

Django Exceptions¶

Django raises some of its own exceptions as well as standard Python exceptions.

Django Core Exceptions¶

Django core exception classes are defined in django.core.exceptions .

AppRegistryNotReady ¶

This exception is raised when attempting to use models before the app loading process , which initializes the ORM, is complete.

ObjectDoesNotExist ¶

The base class for Model.DoesNotExist exceptions. A try/except for ObjectDoesNotExist will catch DoesNotExist exceptions for all models.

EmptyResultSet ¶

EmptyResultSet may be raised during query generation if a query won’t return any results. Most Django projects won’t encounter this exception, but it might be useful for implementing custom lookups and expressions.

FullResultSet ¶

FullResultSet may be raised during query generation if a query will match everything. Most Django projects won’t encounter this exception, but it might be useful for implementing custom lookups and expressions.

FieldDoesNotExist ¶

The FieldDoesNotExist exception is raised by a model’s _meta.get_field() method when the requested field does not exist on the model or on the model’s parents.

MultipleObjectsReturned ¶

The base class for Model.MultipleObjectsReturned exceptions. A try/except for MultipleObjectsReturned will catch MultipleObjectsReturned exceptions for all models.

SuspiciousOperation ¶

The SuspiciousOperation exception is raised when a user has performed an operation that should be considered suspicious from a security perspective, such as tampering with a session cookie. Subclasses of SuspiciousOperation include:

  • DisallowedHost
  • DisallowedModelAdminLookup
  • DisallowedModelAdminToField
  • DisallowedRedirect
  • InvalidSessionKey
  • RequestDataTooBig
  • SuspiciousFileOperation
  • SuspiciousMultipartForm
  • SuspiciousSession
  • TooManyFieldsSent
  • TooManyFilesSent

If a SuspiciousOperation exception reaches the ASGI/WSGI handler level it is logged at the Error level and results in a HttpResponseBadRequest . See the logging documentation for more information.

SuspiciousOperation is raised when too many files are submitted.

PermissionDenied ¶

The PermissionDenied exception is raised when a user does not have permission to perform the action requested.

ViewDoesNotExist ¶

The ViewDoesNotExist exception is raised by django.urls when a requested view does not exist.

MiddlewareNotUsed ¶

The MiddlewareNotUsed exception is raised when a middleware is not used in the server configuration.

ImproperlyConfigured ¶

The ImproperlyConfigured exception is raised when Django is somehow improperly configured – for example, if a value in settings.py is incorrect or unparseable.

FieldError ¶

The FieldError exception is raised when there is a problem with a model field. This can happen for several reasons:

  • A field in a model clashes with a field of the same name from an abstract base class
  • An infinite loop is caused by ordering
  • A keyword cannot be parsed from the filter parameters
  • A field cannot be determined from a keyword in the query parameters
  • A join is not permitted on the specified field
  • A field name is invalid
  • A query contains invalid order_by arguments
Читайте также:  How to get class name python

ValidationError ¶

The ValidationError exception is raised when data fails form or model field validation. For more information about validation, see Form and Field Validation , Model Field Validation and the Validator Reference .

NON_FIELD_ERRORS ¶

ValidationError s that don’t belong to a particular field in a form or model are classified as NON_FIELD_ERRORS . This constant is used as a key in dictionaries that otherwise map fields to their respective list of errors.

BadRequest ¶

The BadRequest exception is raised when the request cannot be processed due to a client error. If a BadRequest exception reaches the ASGI/WSGI handler level it results in a HttpResponseBadRequest .

RequestAborted ¶

The RequestAborted exception is raised when an HTTP body being read in by the handler is cut off midstream and the client connection closes, or when the client does not send data and hits a timeout where the server closes the connection.

It is internal to the HTTP handler modules and you are unlikely to see it elsewhere. If you are modifying HTTP handling code, you should raise this when you encounter an aborted request to make sure the socket is closed cleanly.

SynchronousOnlyOperation ¶

The SynchronousOnlyOperation exception is raised when code that is only allowed in synchronous Python code is called from an asynchronous context (a thread with a running asynchronous event loop). These parts of Django are generally heavily reliant on thread-safety to function and don’t work correctly under coroutines sharing the same thread.

If you are trying to call code that is synchronous-only from an asynchronous thread, then create a synchronous thread and call it in that. You can accomplish this is with asgiref.sync.sync_to_async() .

URL Resolver exceptions¶

URL Resolver exceptions are defined in django.urls .

Resolver404 ¶

The Resolver404 exception is raised by resolve() if the path passed to resolve() doesn’t map to a view. It’s a subclass of django.http.Http404 .

NoReverseMatch ¶

The NoReverseMatch exception is raised by django.urls when a matching URL in your URLconf cannot be identified based on the parameters supplied.

Database Exceptions¶

Database exceptions may be imported from django.db .

Django wraps the standard database exceptions so that your Django code has a guaranteed common implementation of these classes.

exception Error ¶ exception InterfaceError ¶ exception DatabaseError ¶ exception DataError ¶ exception OperationalError ¶ exception IntegrityError ¶ exception InternalError ¶ exception ProgrammingError ¶ exception NotSupportedError ¶

The Django wrappers for database exceptions behave exactly the same as the underlying database exceptions. See PEP 249, the Python Database API Specification v2.0, for further information.

As per PEP 3134, a __cause__ attribute is set with the original (underlying) database exception, allowing access to any additional information provided.

Читайте также:  Num to words python

exception models. ProtectedError ¶

Raised to prevent deletion of referenced objects when using django.db.models.PROTECT . models.ProtectedError is a subclass of IntegrityError .

exception models. RestrictedError ¶

Raised to prevent deletion of referenced objects when using django.db.models.RESTRICT . models.RestrictedError is a subclass of IntegrityError .

HTTP Exceptions¶

HTTP exceptions may be imported from django.http .

UnreadablePostError ¶

UnreadablePostError is raised when a user cancels an upload.

Sessions Exceptions¶

Sessions exceptions are defined in django.contrib.sessions.exceptions .

SessionInterrupted ¶

SessionInterrupted is raised when a session is destroyed in a concurrent request. It’s a subclass of BadRequest .

Transaction Exceptions¶

Transaction exceptions are defined in django.db.transaction .

TransactionManagementError ¶

TransactionManagementError is raised for any and all problems related to database transactions.

Testing Framework Exceptions¶

Exceptions provided by the django.test package.

RedirectCycleError ¶

RedirectCycleError is raised when the test client detects a loop or an overly long chain of redirects.

Python Exceptions¶

Django raises built-in Python exceptions when appropriate as well. See the Python documentation for further information on the Built-in Exceptions .

Additional Information

Support Django!

Contents

  • Django Exceptions
    • Django Core Exceptions
      • AppRegistryNotReady
      • ObjectDoesNotExist
      • EmptyResultSet
      • FullResultSet
      • FieldDoesNotExist
      • MultipleObjectsReturned
      • SuspiciousOperation
      • PermissionDenied
      • ViewDoesNotExist
      • MiddlewareNotUsed
      • ImproperlyConfigured
      • FieldError
      • ValidationError
        • NON_FIELD_ERRORS
        • Resolver404
        • NoReverseMatch
        • UnreadablePostError
        • SessionInterrupted
        • TransactionManagementError
        • RedirectCycleError

        Browse

        You are here:

        Getting help

        FAQ Try the FAQ — it’s got answers to many common questions. Index, Module Index, or Table of Contents Handy when looking for specific information. django-users mailing list Search for information in the archives of the django-users mailing list, or post a question. #django IRC channel Ask a question in the #django IRC channel, or search the IRC logs to see if it’s been asked before. Django Discord Server Join the Django Discord Community. Official Django Forum Join the community on the Django Forum. Ticket tracker Report bugs with Django or Django documentation in our ticket tracker.

        Download:

        Offline (Django 4.2): HTML | PDF | ePub
        Provided by Read the Docs.

        Источник

        Django Exception Handling – A Brief How-To

        Django Exception Handling

        In this article, we will learn Django exception handling in a very brief and concise manner while covering most of the exceptions and error messages in Django.

        Why do we need to handle exceptions?

        As a developer, you will encounter various errors either while making the web APIs, templates, or while writing any other piece of code.

        Dealing with them is a very time taking process but also is an essential task, and hence this critical skill of exceptions and error handling comes into the picture.

        What are Exceptions?

        Exceptions in coding are those types of events that lead to undesirable events. These are detected by run-time executives(like consoles and terminals) or by Operating Systems.

        They need not necessarily stop the whole program but will lead to undesirable outputs.

        Let’s say the client wants to see a particular object from the database. But for some reason, that specific object is not present there.

        In this case, the server won’t come to a halt, but the client will get an error since the object is not present in the DB, which is undesirable.

        The key difference between Exceptions and Errors

        Errors are those events due to which the whole system will come to a halt, and the program will not execute.

        Nothing can be done with errors; we can only detect and then make appropriate changes such that they don’t happen.

        On the other hand, exceptions are something that the developers can deal with without letting the system come to a halt.

        Types of Django Exceptions

        Exception Handling

        There are many kinds of exceptions in Django, out of which five are extremely important and are used most frequently.

        • Django Exception classes
        • Django URL Resolver Exceptions
        • Django Database Exceptions
        • Django Http Exceptions
        • Django Transaction Exceptions

        We will learn about them in detail.

        1) Django Exception classes

        Admin

        • Now in views.py, the code to show a particular item with an id = nm will be:
        def Item(request,nm): item = ItemModel.objects.get(id = nm) return HttpResponse(item)

        Run the server and check for an object not present in DB, say id = 4

        You will get an error message

        DoesNotExist

        Now we will use Django Exception Handling to handle this error. Edit the code in views.py as follows:

        def Item(request,nm): try: item = ItemsModel.objects.get(id = nm) except ItemsModel.DoesNotExist: return HttpResponse('Exception: Data Not Found') return HttpResponse(item)

        Notice the line “except ItemsModel.DoesNotExist“. This is where Python automatically captures the exception. You can replace the exception with one of the exceptions from the list above, and handle the same with a custom error message.

        from django.core.exceptions import *

        That’s it, now we can go on and add exception we want

        def Item(request,nm): try: item = ItemsModel.objects.get(id = nm) except ObjectDoesNotExist: print('Data Not Found') return HttpResponse(item)

        Now run the server and search for id = 4

        Exception Handling

        Similarly, we will handle other important and most used exceptions from the django.core.exceptions

        Some other important Exceptions

        First we will have to import the library

        from django.core.exceptions import

        Lets go through the important exceptions

        Field Dos Not Exist

        This happens when the model field does not exist

        try: Model.objects.get( = '') except FieldDoesNotExist: print('The Field is missing')

        Multiple Objects Returned

        Happens when more than one object in DB has same value for a certain field

        try: Model.objects.get( = '') except MultipleObjectsReturned: print('More than one object with the same name are present in the Database')

        View Does Not Exist

        Happens when we call a view through path() in urls.py , but the view does not exist.

        try: path('item/', ) except ViewDoesNotExist: print('The View does not exist in views.py')

        Validation Error

        Happens when certain information in the form data is not valid

        data = form.cleaned_data['name'] if '' not in data: raise ValidationError('This name does not exist')

        Conclusion

        That’s it, fellas! I do hope that this article helped increase your knowledge and understanding of Django exceptions. Do refer to the official documentation for more information.

        Источник

Оцените статью