0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Django】TypeErrorに遭遇した

Last updated at Posted at 2024-01-03

はじめてのDjangoアプリ作成その4でエラーに遭遇した。
エラーメッセージは

TypeError at /polls/1/vote/
cannot unpack non-iterable int object

というもの。
結論として、原因はquestion = get_object_or_404(Question, question_id)pk=question_idとせず直で渡していたためであった。
直とDjangoがKeyと認識できなかったものと推測。
なおコードは以下の通り。

def vote(request, question_id):
    question = get_object_or_404(Question, 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,)))
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?