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

ⅰ亾dé卋堺 提交于 2019-12-04 05:04:13

You'll receive this error when you're trying to cast a string to an integer, but the string doesn't really contain any digits:

i.e.

number = int(string)

From your code, there are three places where I see the use and probable cast of an integer. When p=get_object_or_404(Poll, pk=poll_id) we're making an assumption that you've correctly passed in an integer as poll_id. Could you post the urlpattern you're using associated with this view and an example URL?

You also are making an assumption that request.POST['choice'] will be an integer and can be cast as such. You aren't catching an exception related to this, so you'll want to check what the value of this entry is. I would add in a few other checks for this part:

if request.method=="POST":
    choice = request.POST.get('choice', None)
    if choice is not None:
        selected_choice = p.choice_set.get(pk=choice)
...

These two stand out the most.

Please post your urlpattern and more of the error message you were getting (such as which specific line is throwing your exception).

Yes, I had the same error, the problem as explained by @cianof was in the template polls/detail.html and in others templates. The error occurs when you paste the code from the tutorial and you have 80 character of margin in your editor.

<input type="radio" name="choice" id="choice {{ forloop.counter }}" value="{{
choice.id }}" />

This will not works because choice.id is close to the braces {{choice.id }}, you should always leave a space between: {{ choice.id }}

About the casting answer posted by @garromark, I can't say anything, I'm new in Python and Django cooding.

I had this error too.

My my case it I had a typo in my form template. Double check the poll detail template (“polls/detail.html”) for typos.

Asmo

I was receive similar error. Problem was hidden here:

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

I had the same error occurred. I found out what was wrong, turns out it was just some little details: First,In my 'polls/detail.html' template, there is an input:

<input type="radio" name="choice" id="choice {{forloop.counter}}" value="{{choice.id}}"/> I had {{choice_id}} before that's why it didn't get the value.

Second, another error said my 'polls/result.html' was not found, then I went into this template I found a stupid mistake:

<a href="{% url 'polls:detail' question.id %}">Vote again?</a>

Inside the tag, I had 'polls.detail', no wonder why the template was not found. ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!