gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:39:13 26 4
gpt4 key购买 nike

在我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com