📜  Django例外

📅  最后修改于: 2020-12-31 00:46:55             🧑  作者: Mango

Django例外

异常是导致程序失败的异常事件。为了应对这种情况,Django使用了自己的异常类,并且还支持所有核心Python异常。

Django核心异常类在django.core.exceptions模块中定义。此模块包含以下类。

Django异常类

Exception Description
AppRegistryNotReady It is raised when attempting to use models before the app loading process.
ObjectDoesNotExist The base class for DoesNotExist exceptions.
EmptyResultSet If a query does not return any result, this exception is raised.
FieldDoesNotExist It raises when the requested field does not exist.
MultipleObjectsReturned This exception is raised by a query if only one object is expected, but multiple objects are returned.
SuspiciousOperation This exception is raised when a user has performed an operation that should be considered suspicious from a security perspective.
PermissionDenied It is raised when a user does not have permission to perform the action requested.
ViewDoesNotExist It is raised by django.urls when a requested view does not exist.
MiddlewareNotUsed It is raised when a middleware is not used in the server configuration.
ImproperlyConfigured The ImproperlyConfigured exception is raised when Django is somehow improperly configured.
FieldError It is raised when there is a problem with a model field.
ValidationError It is raised when data validation fails form or model field validation.

Django URL解析器异常

这些异常在django.urls模块中定义。

Exception Description
Resolver404 This exception raised when the path passed to resolve() function does not map to a view.
NoReverseMatch It is raised when a matching URL in your URLconf cannot be identified based on the parameters supplied.

Django数据库异常

django.db模块中定义了以下例外。

Exception Description
DatabaseError It occurs when the database is not available.
IntegrityError It occurs when an insertion query executes.
DataError It raises when data related issues come into the database.

Django Http异常

django.http模块中定义了以下异常。

Exception Description
UnreadablePostError It is raised when a user cancels an upload.

Django交易例外

事务异常在django.db.transaction中定义。

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

Django异常示例

假设我们要获取id = 12的员工记录,我们的视图函数将在下面显示。如果未找到数据,则会引发DidNotExist异常。这是Django的内置例外。

// views.py

def getdata(request):
    data = Employee.objects.get(id=12)
    return HttpResponse(data)

// urls.py

path('get',views.getdata)

它显示以下异常,因为在ID 12处没有可用的记录。

输出:

我们可以使用try和except来处理它,现在让我们处理这个异常。

// Views.py

def getdata(request):
    try:
        data = Employee.objects.get(id=12)
    except ObjectDoesNotExist:
        return HttpResponse("Exception: Data not found")
    return HttpResponse(data);

输出: