Django の例外

Django は普通の Python の例外の他に、いくつか独自の例外も起こします。

Django Core 例外

Django core 例外クラスは django.core.exceptions で定義されています。

AppRegistryNotReady

exception AppRegistryNotReady[ソース]

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

ObjectDoesNotExist

exception ObjectDoesNotExist[ソース]

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

See get().

EmptyResultSet

exception 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.

FieldDoesNotExist

exception 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

exception MultipleObjectsReturned[ソース]

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

See get().

SuspiciousOperation

exception 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

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.

PermissionDenied

exception PermissionDenied[ソース]

PermissionDenied 例外は、ユーザーにリクエストされたアクションを実行する権限がない場合に発生します。

ViewDoesNotExist

exception ViewDoesNotExist[ソース]

ViewDoesNotExist 例外は、リクエストされたビューが存在しないい場合に、django.urls によって発生します。

MiddlewareNotUsed

exception MiddlewareNotUsed[ソース]

MiddlewareNotUsed 例外は、サーバーの設定の中でミドルウェアが使用されなかった時に発生します。

ImproperlyConfigured

exception ImproperlyConfigured[ソース]

ImproperlyConfigured 例外は、Django が何らかの点で不適切に設定されている場合に発生します。たとえば、settings.py に含まれる値が不正であったり、パースできないような場合が考えられます。

FieldError

exception FieldError[ソース]

FieldError 例外は、モデルのフィールドに問題がある時に発生します。発生理由としては、次のようないくつかの理由が考えられます。

  • 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

ValidationError

exception ValidationError[ソース]

ValidationError 例外は、データがフォームまたはモデルのフィールド検証に失敗すると発生します。検証 (validation) のより詳しい情報については、Form and Field ValidationModel Field ValidationValidator Reference を参照してください。

NON_FIELD_ERRORS

NON_FIELD_ERRORS

ValidationErrors 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

exception BadRequest[ソース]
New in Django 3.2.

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

exception 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

exception 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 の例外

URL Resolver の例外は django.urls で定義されています。

Resolver404

exception 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

exception NoReverseMatch

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

データベースの例外

データベースの例外は 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.

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

exception UnreadablePostError

UnreadablePostError は、ユーザーがアップロードをキャンセルすると発生します。

Sessions Exceptions

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

SessionInterrupted

exception SessionInterrupted[ソース]
New in Django 3.2.

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

トランザクションの例外

トランザクションの例外は django.db.transaction で定義されています。

TransactionManagementError

exception TransactionManagementError[ソース]

TransactionManagementError が発生するのは、データベースのトランザクションに関するあらゆる問題に対してです。

テストフレームワークの例外

django.test パッケージが提供する例外です。

RedirectCycleError

exception client.RedirectCycleError

RedirectCycleError は、テストクライアントがループまたは過度に長いリダイレクトチェーンを検出した時に発生します。

Python の例外

Django は、十分適切な場合にはビルトインの Python の例外を起こします。詳しい情報については、Python のドキュメント Built-in Exceptions を読んでください。