I want to get the exception text when I save value into the database.

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 ???)
有帮助吗?

解决方案

You can pass a 2nd variable on the except statement. It will hold the text error. See below

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)

其他提示

You can print exception as given below.

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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top