如何在Django视图中使用异常处理 [英] How to use exception handling in Django view
问题描述
假设我有这个代码
if form.is_valid():
form.save()
现在假设我的表单有效我有异常,foregin键值链接到多个列,所以它将引发例外
现在我想知道有没有办法抓住该异常值,并通过AJAX传递给jquery
因为表单是有效的,所以它进入循环,但不能在 form.save
那么我如何编程,如果异常发生,它会传递给jquery像
如果异常
返回HttpResponse(异常)
我得到这个例外
MultipleObjects返回
/ manage / Source / create / get()返回
多个帐户 - 它返回
3!查找参数是
{'account_number':
u'121121'}
什么类型的异常
MultipleObjectsReturned 是的例外。
try:
/ pre>
#do something
except MultipleObjectsReturned:
return HttpResponse('MultipleObjectsReturned')
我不建议使用一个裸尝试/除了捕获所有异常,因为你不会确切知道是什么问题。
Suppose i have this code
if form.is_valid(): form.save()
Now suppose my form is valid i have exception that foregin key value is linked to more than one column so it will raise exception
Now i want to know is there any way to grab that exception value and pass to jquery via AJAX
Because form is valid so it comes inside the loop but its not able to go after
form.save
So how can i program that if exception occurs it get passed to jquery like
if exception return HttpResponse(exception)
I get this exception
MultipleObjectsReturned at /manage/Source/create/ get() returned more than one Account -- it returned 3! Lookup parameters were {'account_number': u'121121'}
What type of exception it is
解决方案MultipleObjectsReturned is the exception.
try: #do something except MultipleObjectsReturned: return HttpResponse('MultipleObjectsReturned')
I wouldn't recommend using a bare try/except to catch all exceptions, as you won't know exactly what's wrong.
这篇关于如何在Django视图中使用异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!