Django:捕捉完整性错误并使用模板显示自定义消息 [英] Django: Catching Integrity Error and showing a customized message using template

查看:129
本文介绍了Django:捕捉完整性错误并使用模板显示自定义消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的django动力应用程序中,只有一个明显的例子可以出现IntegrityError。所以我怎么能抓住这个错误,并使用模板显示一个消息。

解决方案

只需使用try和catch。

 从django.db import IntegrityError 
从django.shortcuts import render_to_response

try:
#代码生成错误
除了IntegrityError作为e:
返回render_to_response(template.html,{消息:e.message})

如果您希望您可以在模板中使用该消息。 / p>

编辑



感谢 Jill-Jennn Vie ,你应该使用 e .__因为__ 如这里所述


In my django powered app there is only one obvious case where "IntegrityError" can arise.So,how can I catch that error and display a message using templates.

解决方案

Just use try and 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})

If you want you can use the message in your template.

EDIT

Thanks for Jill-Jênn Vie, you should use e.__cause__, as described here.

这篇关于Django:捕捉完整性错误并使用模板显示自定义消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆