Python3尝试多个Except不起作用(Django)

时间:2018-11-24 21:43:16

标签: python django python-3.x try-catch except

我有以下功能

question = get_object_or_404(Question, pk=question_id)
try:
    selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
    return render(request, 'polls/detail.html', {
        'question': question,
        'error_message': "You didn't select a choice.",
    })
else:
    selected_choice.votes += 1
    selected_choice.save()
    return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

当我做一个空的POST时,我得到一个黄色的错误页面,显示

name 'Choice' is not defined. Exception Type:   NameError"

我将除外更改为以下内容:

except KeyError:

现在它可以工作了,但我仍然希望可以选择Choice.DoesNotExist异常。我也想将其保持一行。这是什么问题?

编辑: 我愚蠢了,忘记了“选择”的收录。问题解决了。

0 个答案:

没有答案