在Django视图中,如何更改类成员的值?

时间:2015-03-25 05:33:28

标签: python django webserver

如果他获得投票,我希望增加候选人的赚取价值。所以我在 result_view 中写了这个部分,但它没有用。

以下是我的观点。


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,)

我该如何解决这个问题?

1 个答案:

答案 0 :(得分: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)