首页 > 解决方案 > Python3尝试多个除了不工作(Django)

问题描述

我有以下功能

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 更改为以下内容:

except KeyError:

现在它可以工作了,但我仍然希望有 Choice.DoesNotExist 异常。我也想把它放在一行中。这里有什么问题?

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

标签: pythondjangopython-3.xtry-catchexcept

解决方案


推荐阅读