在我的django驱动的应用程序中,只有一种明显的情况会出现“ IntegrityError”。
因此,如何捕获该错误并使用模板显示消息?
只需尝试并抓住。
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})
如果需要,可以在模板中使用该消息。
编辑
感谢吉尔-爵Vie的,你应该使用e.__cause__
,因为这里描述。