0

Django 1.6 と Python 2.7 を使用しています。基本的に私は投票アプリケーションを作成しており、ラジオ ボタンから選択した選択肢 (「市民」) を取得し、選択した市民を 1 対 1 のキーとして使用して「最高の市民」をインスタンス化しようとしています。

ここに私のモデルがあります:

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 と評価されていますが、それ以外は決して実行されません。印刷テストを使用していますが、コマンド プロンプトに表示されません。

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