i am learning django from official django tutorial. and i am getting this error when vote something from form. this caused from - probably - vote function under views.py
here is my views.py / vote function :
def vote(request,poll_id):
p=get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render_to_response('polls/detail.html', {'poll':p,
'error_message' : "didint select anything ",}, context_instance= RequestContext(request))
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls.views.results', args=(p.id,)))
and this is error message screen :
**ValueError at /polls/2/vote/
invalid literal for int() with base 10: 'on'**
Request Method: POST Request URL: 127.0.0.1:8000/polls/2/vote/
Django Version: 1.4 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: 'on' Exception Location: /usr/local/lib/python2.7/dist-packages/django/db/models/fields/init.py in get_prep_value, line 537
and here is my polls/urls.py :
from django.conf.urls import patterns, include, url
urlpatterns = patterns('polls.views',
url(r'^$', 'index'),
url(r'^(?P<poll_id>\d+)/$','detail'),
url(r'^(?P<poll_id>\d+)/results/$','results'),
url(r'^(?P<poll_id>\d+)/vote/$','vote'),
)
and here is project/urls.py :
from django.conf.urls import patterns, include, url
urlpatterns = patterns('polls.views',
url(r'^$', 'index'),
url(r'^(?P<poll_id>\d+)/$','detail'),
url(r'^(?P<poll_id>\d+)/results/$','results'),
url(r'^(?P<poll_id>\d+)/vote/$','vote'),
)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With