我希望在将值保存到数据库时获取异常文本。
view.py:
if request.method == 'POST':
form = CustomerForm(request.POST)
if form.is_valid():
try:
customer = form.save(commit=False)
customer.save()
except DatabaseError:
message = 'Database Error: ' + str(??? text error ???)
答案 0 :(得分:2)
您可以在except
语句中传递第二个变量。它会保留文本错误。见下文
if request.method == 'POST':
form = CustomerForm(request.POST)
if form.is_valid():
try:
customer = form.save(commit=False)
customer.save()
except DatabaseError, text_error:
message = u'Database Error: {0}'.format(text_error)
答案 1 :(得分:0)
您可以按以下方式打印例外。
if request.method == 'POST':
form = CustomerForm(request.POST)
if form.is_valid():
try:
customer = form.save(commit=False)
customer.save()
except DatabaseError as e:
message = 'Database Error: ' + str(e.message)