python - Django:捕获完整性错误并使用模板显示自定义消息

标签 python django

在我的 django 应用程序中,只有一种明显的情况会出现“IntegrityError”。
那么,我如何才能捕获该错误并使用模板显示消息?

最佳答案

只需使用 try 和 catch。

from django.db import IntegrityError
from django.shortcuts import render_to_response

try:
    # code that produces error
except IntegrityError as e:
    return render_to_response("template.html", {"message": e.message})

如果您愿意,可以使用模板中的消息。

编辑

感谢 Jill-Jênn Vie , 你应该使用 e.__cause__, as described here .

关于python - Django:捕获完整性错误并使用模板显示自定义消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11293380/

相关文章:

python - 我无法将 MySQL 版本 8 连接到 Django 2.2 项目

python - 尝试将预测带回到数据帧中的相应行

python - peewee 的 get 方法如何知道如何生成 where 子句?

python - 在 python 中解析来自 WIZ110SR 的 TCP/IP 串行数据

python - Tastypie Dehydrate 反向关系计数

django - 可能在 pythonanywhere.com 上有 React + Django

django - 在 Django 中将计算值从 View 保存到模型

python - 具有 '__in' 过滤器性能的 Django ORM values_list

Python 和变量传递

python - 如何在 keras/tensorflow 中定义秩大于 4 的张量上的 2D 卷积