python - 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 异常。我也想把它放在一行中。这里有什么问题?
编辑:我忘记了“选择”的包含,愚蠢的我。问题解决了。
解决方案
推荐阅读
- docker - 为什么 Kubernetes 服务无法在 Minikube 上正常运行?(拒绝连接)
- php - 在 laravel 迁移中保存加密价格值
- javascript - 像下面这样在 Javascript 中将方法传递给基类的目的是什么?
- firebase - 如何从 firebase 服务器获取 firebase 功能 - 我在本地没有
- php - Laravel - 如何将集合复制到新变量
- labview - 在LabVIEW中创建虚拟通道的数学方程
- deep-learning - DDPG 中的演员评论家损失
- android - 如何使用 View Model 和 Live Data 将参数传递给我的 Word Dao 进行查询?
- sql-server - 使用节点连接本地 SQL Server 失败
- reactjs - 将反应站点发布到 github.io 时出错