Django2.0教程投票页报错:'ReverseManyToOneDescriptor'无get属性
解决Django投票功能的AttributeError错误
嘿,别着急,这个问题其实很好搞定,我给你掰扯明白哈!
错误核心原因
你看到的 AttributeError: 'ReverseManyToOneDescriptor' object has no attribute 'get',根源就在这行代码:
selected_choice = Question.choice_set.get(pk=request.POST['choice'])
choice_set 是**单个Question实例(也就是具体某一个投票问题)**才有的属性,你现在直接用Question这个模型类去调用它,就像你想让“猫”这个物种去抓老鼠,但得找一只具体的猫咪才行呀!直接调用类得到的是一个描述符对象,它没有get方法,所以报错了。
一步步修改方案
- 先根据传入的
question_id,获取到具体的那个投票问题实例,在try块前面加一行代码:
(用question = get_object_or_404(Question, pk=question_id)get_object_or_404比直接Question.objects.get更友好,找不到对应id的问题时会返回404页面,而不是直接抛出错误) - 把原来的
Question.choice_set.get改成用这个实例来调用:selected_choice = question.choice_set.get(pk=request.POST['choice']) - 这一步还顺便解决了你后面代码里
question.id未定义的问题(之前你没定义question变量,现在有了)。
修改后的完整vote函数
from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.urls import reverse from .models import Choice, Question def vote(request, question_id): # 获取具体的投票问题实例 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() # 成功处理POST后必须重定向,防止用户点后退重复提交数据 return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
额外小提醒
我看到你的DetailView里模板名写的是'polls/details.html'(带s),但vote函数里渲染的是'polls/detail.html'(不带s),如果后面遇到模板找不到的错误,记得检查这个拼写是否一致哦!
内容的提问来源于stack exchange,提问作者StupidQuestionGuy
相关产品推荐
相关产品推荐

