Search code examples
pythondjangopython-3.6web-frameworks

Field 'id' expected a number but got 'on'


I am doing a project included in Django Documentation.

When I enter URL http://localhost:8000/polls/1/vote/ I will get the error at below line:

invalid literal for int() with base 10: 'on'

Below lines are my view definition:

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()
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))


Solution

  • you have sent the value "on" in a post message with the field request.POST["choice"] , which is not a valid pk for selected_choice = question.choice_set.get(pk=request.POST['choice']) which expects a number