所以我把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
views.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]))
urls.py:
url(r'^revote/(\d+)/$', 'blog.views.vote_again'),
url(r'^polls/(?P<poll_id>\d+)/vote/$', 'blog.views.vote'),
这一切都适用于第一篇帖子和民意调查,但当我想将民意调查添加到没有相同pk的帖子时,它会崩溃。
任何帮助或指示将不胜感激。我已经乱了大约2个小时,这是django第一次让我感到沮丧。提前道歉,因为我99%肯定这是一个愚蠢的问题。
答案 0 :(得分:1)
pk
表示主键。所以你试图获得一个id与post_pk相同的poll对象。
尝试,
p = get_object_or_404(Poll, post_id=post_pk)