0

我正在使用 Django 1.6 和 Python 2.7。基本上我正在制作一个投票应用程序,我试图从一个单选按钮中获取选定的选项(“公民”),然后使用选定的公民作为一对一键来实例化一个“最佳公民”。

这是我的模型:

class Citizen(models.Model):
    name = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    can_best = models.BooleanField(False)

    def __unicode__(self):
        return self.name

class Best_Citizen(models.Model):
    name = models.CharField(max_length=200)
    citizen = models.OneToOneField(Citizen)

    def __unicode__(self):
        return self.name

网址.py:

urlpatterns = patterns('',
    # Examples:
    # url(r'^blog/', include('blog.urls')),

    url(r'^$', views.index, name='index'),
    url(r'^choose_best/$', views.choose_best, name='choose_best'),
    url(r'^(?P<citizen_id>\d+)/$', views.detail, name='detail'),
    url(r'^admin/', include(admin.site.urls)),
)

我的“choose_best”观点没有达到我的预期。显然,try 子句评估 OK,但 else 永远不会运行。我正在使用打印测试,但它没有出现在我的命令提示符中。

def index(request):

    citizens = Citizen.objects.all()
 #   citizens = get_list_or_404(Citizen)
    for citizen in citizens: 
        if citizen.votes >= 3:
            citizen.can_best = True
            citizen.save()

    return render(request, 'best_app/index.html', {'citizens':citizens})

def detail(request, citizen_id):

    try:
        citizen = Citizen.objects.get(pk=citizen_id)
    except Citizen.DoesNotExist:
        print "raise Http404"
    return render(request, 'best_app/detail.html', {'citizen':citizen})
 #   return HttpResponse("You're looking at poll %s." % citizen.name)

def choose_best(request):

    best_candidates = Citizen.objects.filter(can_best=True)     # narrow down the candidates for best citizen to those with >= 3 votes

    if request.method == 'POST':

        try:
            selected_choice = best_candidates.get(pk=request.POST['citizen'])
        except (KeyError, Citizen.DoesNotExist):

            return render(request, 'index.html')
        else:   
            print "selected choice is: ", selected_choice
            Best_Citizen.objects.all().delete()                 # Current best citizen is deleted to make way for new best citizen
            new_best = Best_Citizen(citizen=selected_choice)    
            new_best.save()
            return render(request, 'best_app/index.html', {'new_best':new_best})

    else:
        return render(request, 'best_app/choose_best.html', {'best_candidates':best_candidates})    

我希望浏览器返回 index.html,但最后的 else 子句会立即被评估。我究竟做错了什么?感谢任何人的帮助。

4

0 回答 0