I am trying to follow part 4 of the polls app tutorial. I am new to Django and not very experienced with Python or programming in general.
My problem is throwing an error message when "Vote" is pressed without a choice being selected.
polls/views.py:
It is my understanding that when request.POST doesn't get a choice ID, it executes 'except', displaying the voting page again (detail.html) and an error message. However it simply displays "NameError global name 'Choice' is not defined" page.
Can someone help me figure out what I'm doing wrong?
-- My problem is throwing an error message when "Vote" is pressed without a choice being selected.
polls/views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader
from django.core.urlresolvers import reverse
from polls.models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = RequestContext(request, {
'latest_question_list': latest_question_list,
})
return HttpResponse(template.render(context))
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
def vote(request, question_id):
p = get_object_or_404(Question, pk=question_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': p,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
It is my understanding that when request.POST doesn't get a choice ID, it executes 'except', displaying the voting page again (detail.html) and an error message. However it simply displays "NameError global name 'Choice' is not defined" page.
Can someone help me figure out what I'm doing wrong?
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/0bf39ec4-709e-4ad8-85df-3a2aeb31c83d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment