我即将完成投票应用程序的构建,除了结果页面外,一切似乎都在工作。在我输入选择后,“再次投票”或任何其他数据都没有出现。看起来页面正在重新加载。新选票正在计算中,我没有收到错误消息。我可以看到我在 /results/ 页面上。
有没有人有任何想法我应该在哪里寻找问题?
谢谢!
意见:
# Create your views here.
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from polls.models import Choice, Poll
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_poll_list'
def get_queryset(self):
"""Return the last five published polls."""
return Poll.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Poll
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Poll
template_name = 'polls/results.hmtl'
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):
# Redisplay the poll voting form.
return render(request, 'polls/detail.html', {
'poll': p,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
#Always return an HttpRespsonseRedirect 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,)))
网址 -
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
#ex: /polls/
url(r'^$', views.IndexView.as_view(), name='index'),
#ex: /polls/5/
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
# ex: /polls/5/results/
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
#ex: /polls/5/vote/
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)
楷模
from django.db import models
import datetime
from django.utils import timezone
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __unicode__(self):
return self.choice_text
希望我在这里粘贴时没有弄乱任何格式。