尝试,除了,否则没有做我期望它在获取发布数据(Django)

时间:2014-01-11 01:13:48

标签: python django post try-except

我正在使用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

urls.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,但是从不运行。我正在使用打印测试,它没有显示在我的命令promt中。

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子句。我究竟做错了什么?感谢任何人的帮助。

0 个答案:

没有答案