如何对失败的Django事务做出反应?例如,返回某种错误页面或重新加载页面等。
代码中有with transaction.atomic()
,以防用户保存但在保存userprofile期间出现问题,所有内容都将被回滚。
但是当事务失败以便回滚时,如何检测并对情况作出反应?
if request.method == 'POST':
if register_as_translator_form.is_valid():
cleaned = register_as_translator_form.cleaned_data
with transaction.atomic():
request.user.first_name = cleaned['first_name']
request.user.last_name = cleaned['last_name']
request.user.userprofile.IBAN = cleaned['IBAN']
languages = cleaned['languages']
language_levels = get_or_create_unknown_language_levels(languages)
request.user.userprofile.language_levels.add(*language_levels)
request.user.save()
request.user.userprofile.is_translator = True
request.user.userprofile.save()
return HttpResponseRedirect('/register-translator-success')
答案 0 :(得分:0)
您可以捕获异常(除了-test)并返回错误消息/页面。
try:
with transaction.atomic():
request.user.first_name = cleaned['first_name']
request.user.last_name = cleaned['last_name']
request.user.userprofile.IBAN = cleaned['IBAN']
languages = cleaned['languages']
language_levels = get_or_create_unknown_language_levels(languages)
request.user.userprofile.language_levels.add(*language_levels)
request.user.save()
request.user.userprofile.is_translator = True
request.user.userprofile.save()
return HttpResponseRedirect('/register-translator-success')
except:
return HttpResponseRedirect('/register-translator-failure')