因此,我將django-polls教程帶入了一個簡單的博客。一些帖子通過外鍵將它們鏈接到它們。我遇到的問題是當我「投票」或單擊「再投票」它重新加載帖子,但它重新加載使用該投票的ID。在django中返回多個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%肯定這是一個愚蠢的問題。
如果你也添加型號代碼這是更好。 – Babu 2012-07-27 05:12:47
只需添加它們。另外,我還沒有使用用戶,只有我可以投票並重新投票。 – lciamp 2012-07-27 05:19:57
在'def vote_again(request,post_pk)'語義上,你傳遞post_pk,但是查詢Poll模型。這是打算嗎? – Babu 2012-07-27 05:30:44