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