Python 为什么在尝试访问HttpRequest.POST[';choice';]值时出现类型错误?如何解决此错误?

Python 为什么在尝试访问HttpRequest.POST[';choice';]值时出现类型错误?如何解决此错误?,python,django,python-3.x,django-templates,httprequest,Python,Django,Python 3.x,Django Templates,Httprequest,我最近一直在学习django教程,我被卡住了。在使用post方法提交表单后,我尝试使用.get()方法获取所选的_choice模型对象,但得到一个TypeError:无法解包不可编辑的ModelBase对象错误 以下是视图 from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from django.urls import reverse from

我最近一直在学习django教程,我被卡住了。在使用post方法提交表单后,我尝试使用.get()方法获取所选的_choice模型对象,但得到一个TypeError:无法解包不可编辑的ModelBase对象错误

以下是视图

from django.shortcuts import render, get_object_or_404

from django.http import HttpResponseRedirect
from django.urls import reverse
from .models import Question, Choice

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(Question, pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {'question': question, 'error_message': 'Please select a choice and vote'})
    else:
        selected_choice.no_of_votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:result', args=(question.id,)))

def result(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/result.html', {'question': question})
以下是模板

from django.shortcuts import render, get_object_or_404

from django.http import HttpResponseRedirect
from django.urls import reverse
from .models import Question, Choice

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(Question, pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {'question': question, 'error_message': 'Please select a choice and vote'})
    else:
        selected_choice.no_of_votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:result', args=(question.id,)))

def result(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/result.html', {'question': question})
  • detail.html

    
    {% block content_main %}
    
    <h2>{{question.question_text}}</h2>
    {% if error_message %} <strong>{{error_message}}</strong><br><br> {% endif %}
    <form action="{% url 'polls:vote' question.id %}" method="post">
    {% csrf_token %}
    {% for choice in question.choice_set.all %}
        <input type="radio" name="choice" id="choice{{forloop.counter}}" value="{{choice.id}}" style="margin-left: 20px;">
        <label for="choice{{forloop.counter}}" style="font-size: 20px;">{{choice.choice_text}}</label><br><br>
    {% endfor %} <br>
        <input type="submit" value="vote" style="margin-left: 30px; font-size: 20px;">
    </form>
    
    {% endblock %}
    
    在终端中,

    >[14/Nov/2019 00:52:14] "GET / HTTP/1.1" 404 2027 Not
    > Found: /favicon.ico [14/Nov/2019 00:52:16] "GET /favicon.ico HTTP/1.1"
    > 404 2078 [14/Nov/2019 00:52:24] "GET /polls/ HTTP/1.1" 200 447
    > [14/Nov/2019 00:52:27] "GET /polls/1/ HTTP/1.1" 200 1145 Internal
    > Server Error: /polls/1/vote Traceback (most recent call last):   File
    > "C:\Users\Neeyat\PycharmProjects\DjangoApps\Polls\venv\lib\site-packages\django\core\handlers\exception.py",
    > line 34, in inner
    >     response = get_response(request)   File "C:\Users\Neeyat\PycharmProjects\DjangoApps\Polls\venv\lib\site-packages\django\core\handlers\base.py",
    > line 115, in _get_response
    >     response = self.process_exception_by_middleware(e, request)   File "C:\Users\Neeyat\PycharmProjects\DjangoApps\Polls\venv\lib\site-packages\django\core\handlers\base.py",
    > line 113, in _get_response
    >     response = wrapped_callback(request, *callback_args, **callback_kwargs)   File "C:\Users\Neeyat\PycharmProjects\DjangoApps\Polls\mysite\polls\views.py",
    > line 28, in vote
    >     selected_choice = question.choice_set.get(Question, pk=request.POST['choice'])   File
    > "C:\Users\Neeyat\PycharmProjects\DjangoApps\Polls\venv\lib\site-packages\django\db\models\manager.py",
    > line 82, in manager_method
    >     return getattr(self.get_queryset(), name)(*args, **kwargs)   File "C:\Users\Neeyat\PycharmProjects\DjangoApps\Polls\venv\lib\site-packages\django\db\models\query.py",
    > line 399, in get
    >     clone = self.filter(*args, **kwargs)   File "C:\Users\Neeyat\PycharmProjects\DjangoApps\Polls\venv\lib\site-packages\django\db\models\query.py",
    > line 892, in filter
    >     return self._filter_or_exclude(False, *args, **kwargs)   File "C:\Users\Neeyat\PycharmProjects\DjangoApps\Polls\venv\lib\site-packages\django\db\models\query.py",
    > line 910, in _filter_or_exclude
    >     clone.query.add_q(Q(*args, **kwargs))   File "C:\Users\Neeyat\PycharmProjects\DjangoApps\Polls\venv\lib\site-packages\django\db\models\sql\query.py",
    > line 1290, in add_q
    >     clause, _ = self._add_q(q_object, self.used_aliases)   File "C:\Users\Neeyat\PycharmProjects\DjangoApps\Polls\venv\lib\site-packages\django\db\models\sql\query.py",
    > line 1318, in _add_q
    >     split_subq=split_subq, simple_col=simple_col,   File "C:\Users\Neeyat\PycharmProjects\DjangoApps\Polls\venv\lib\site-packages\django\db\models\sql\query.py",
    > line 1187, in build_filter
    >     arg, value = filter_expr TypeError: cannot unpack non-iterable ModelBase object [14/Nov/2019 00:52:30] "POST /polls/1/vote HTTP/1.1"
    > 500 102541
    

    我刚开始做后端web开发,我在任何地方都找不到解决方案。请帮我解决这个问题。提前谢谢。

    您的
    视图中有一点小错误。py

    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']) # <-- here
        except (KeyError, Choice.DoesNotExist):
            return render(request, 'polls/detail.html', {'question': question, 'error_message': 'Please select a choice and vote'})
        else:
            selected_choice.no_of_votes += 1
            selected_choice.save()
            return HttpResponseRedirect(reverse('polls:result', args=(question.id,)))
    
    def投票(请求,问题编号):
    问题=获取对象或404(问题,主键=问题id)
    尝试:
    所选内容=问题.choice\u集.get(pk=request.POST['choice'])#
    
    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']) # <-- here
        except (KeyError, Choice.DoesNotExist):
            return render(request, 'polls/detail.html', {'question': question, 'error_message': 'Please select a choice and vote'})
        else:
            selected_choice.no_of_votes += 1
            selected_choice.save()
            return HttpResponseRedirect(reverse('polls:result', args=(question.id,)))