2015-03-25 47 views
0

我想增加候選人的賺取價值,如果他得票。所以我在result_view中寫了這部分,但它不起作用。在Django視圖中,如何更改類成員的值?

這是我的看法。


from django.shortcuts import render_to_response 

from election.models import * 

# /candidate/ view 
def candidate_view(request): 
    if request.method == 'GET': 
     c = Candidate.objects.all() 
     return render_to_response('candidate.html', {'candidates': c}) 

# /candidate/result/ view 
def result_view(request): 
    if request.method == 'POST': 
     c = Candidate.objects.all() 
     ec = Candidate.objects.filter(num=request.POST.get('choice')) 

     ec[0].earn += 1 
     ec[0].name = 'semi kwon' 
     ec[0].save() 

     #return render_to_response('result.html', {'candidates': ec}) 
     return render_to_response('result.html', {'candidates': c}) 

這是我的模型。


from django.db import models 


class Candidate(models.Model): 

    num = models.IntegerField() 
    name = models.TextField() 
    major = models.TextField() 
    grade = models.IntegerField() 
    earn = models.IntegerField(default = 0, blank=True, editable=True) 

    def __unicode__(self): 
     return "%d : %s"%(self.num, self.name,) 

我怎樣才能解決這個問題?

+0

歡迎進入計算器!爲了更好的可讀性,我編輯了代碼示例的內容。請注意,代碼塊應以4個空格的縮進開頭。如果您可以提供模板的片段,這也是有用的。 – cezar 2015-03-25 06:55:45

+0

你也有一個表單嗎?(像''CandidateForm(ModelForm)'')?在您的''result_view''中,您正在處理應該在表單中完成的用戶輸入,但是您沒有提供所需的代碼。 – cezar 2015-03-25 07:00:06

+0

@cezar感謝您的熱烈歡迎:> !!從現在開始我會記住這一點。 – 2015-03-25 09:56:02

回答

0

更新候選人後是否檢查了數據庫?

由於您在更新候選人(ec)之前獲得候選人(c),您可能已更新候選人,但已將舊套餐傳遞給模板。

這將是更好的使用的一種形式,但爲了保持你的邏輯,試試這個:

def result_view(request): 
    # csrf update etc 
    # your request.method GET here 
    # ... 
    if request.method == 'POST': 
     # dictionary with vars that will be passed to the view 
     params = {} 

     # check if there is a candidate with this num 
     # before you do anything with it 
     # you could do a try/except instead 
     if Candidate.objects.filter(num=request.POST.get('choice')).count(): 
      # Getting candidate 
      candidate = Candidate.objects.get(num=request.POST.get('choice')) 
      # Updating candidate 
      candidate.earn += 1 
      # I don't know what this is, but let's keep it 
      candidate.name = 'semi known' 
      # Saving candidate 
      candidate.save() 

     else: 
      # returning error, candidate not found 
      params['error'] = "No candidate with this num" 

     # updating candidates list 
     params['candidates'] = Candidate.objects.all() 

     # rendering view 
     return render_to_response('result.html', params) 
+0

其實,半功德是我的名字:D ... kkk。我忘了刪除它。 – 2015-03-25 09:48:41

+0

ahaha ...那麼,它工作嗎? – brunofitas 2015-03-25 09:58:23

+0

是的,它的工作原理!非常感謝!! – 2015-03-25 10:00:50

相關問題