0

所以我把 django-polls 教程带进了一个简单的博客。有些帖子通过外键链接到他们的民意调查。我遇到的问题是当我“投票”或单击“再次投票”时,它会重新加载帖子,但会使用投票的 ID 重新加载。

例子:

post1 - linked to - poll1
post2 - no poll
post3 - linked to - poll2

因此,当我在 post3 的投票中再次投票或单击投票时,它会加载 post2。

我需要获取帖子的 ID 和投票。

这是我的代码:models.py:

class Post(models.Model):
    title = models.CharField(max_length=60)
    description = models.CharField(max_length=200)
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)

    def display_mySafeField(self):
        return mark_safe(self.body)

    def __unicode__(self):
        return self.title

class Poll(models.Model):
    question = models.CharField(max_length=200)
    total_votes = models.DecimalField(default=0.0, max_digits=5, decimal_places=2)
    post = models.ForeignKey(Post)
    voted = models.BooleanField(default=False)

    def __unicode__(self):
        return self.question


# Choice for the poll
class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.DecimalField(default=0.0, max_digits=5, decimal_places=2)
    percentage = models.DecimalField(default=0.0, max_digits=5, decimal_places=2)

    def __unicode__(self):
        return self.choice

视图.py:

def vote(request, poll_id):
    global choice
    p = get_object_or_404(Poll, pk=poll_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the poll voting form.
        return render_to_response('post.html', {
            'poll': p,
            'error_message': "You didn't select a choice.",
            }, context_instance=RequestContext(request))
    else:
        selected_choice.votes += 1
        p.total_votes += 1
        selected_choice.save()
        p.voted = True
        p.save()

        choices = list(p.choice_set.all())
        for choice in choices:
            percent = choice.votes*100/p.total_votes
            choice.percentage = percent
            choice.save()

        return HttpResponseRedirect(reverse("blog.views.post", args=[poll_id]))

def vote_again(request, post_pk):
    try:
        p = get_object_or_404(Poll, pk=post_pk)
    except (KeyError, Poll.DoesNotExist):
    # Redisplay the poll voting form.
        return render_to_response('post.html', {
        'poll': p,
        'error_message': "You didn't select a choice.",
        }, context_instance=RequestContext(request))
    else:
        p.voted = False
        p.save()
    return HttpResponseRedirect(reverse("blog.views.post", args=[post_pk]))

网址.py:

url(r'^revote/(\d+)/$', 'blog.views.vote_again'),
url(r'^polls/(?P<poll_id>\d+)/vote/$', 'blog.views.vote'),

这一切都适用于第一个帖子和民意调查,但是当我想将民意调查添加到没有相同 pk 的帖子时它会崩溃。

任何帮助或方向将不胜感激。我已经搞砸了大约 2 个小时,这是 django 第一次让我感到沮丧。提前道歉,因为我 99% 确定这是一个愚蠢的问题。

4

1 回答 1

1

pk表示主键。因此,您正在尝试获取其 id 与 post_pk 相同的轮询对象。

尝试,

p = get_object_or_404(Poll, post_id=post_pk)
于 2012-07-27T05:49:27.467 回答