2012-08-08 49 views
-1

我做了一個簡單的博客和django民意調查教程。我試圖讓他們一起工作。當我加載一篇文章時,與它相關的投票加載,投票再次工作,但當我點擊一個選項,然後投票按鈕,它加載與民意調查ID的ID。林不知道,如果我的「投票」功能的意見,我的「投票」網址,或我的模板搞砸了?這裏是我的代碼:將django民意調查教程應用程序添加到其他應用程序

models.py:

# Post class 
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 

# Poll for the Post 
class Poll(models.Model): 
    question = models.CharField(max_length=200) 
    total_votes = models.IntegerField(default=0) 
    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.IntegerField(default=0) 
    percentage = models.DecimalField(default=0.0, max_digits=5, decimal_places=2) 

    def __unicode__(self): 
     return self.choice 

urls.py:

urlpatterns = patterns('', 
    ### main/index page 
    url(r'^$', 'blog.views.main', name='index'), 

    ### url for the post.html 
    url(r'^post/(\d+)', 'blog.views.post'), 

    ### polls 
    url(r'^polls/(\d+)/results/$', 'blog.views.results'), 
    url(r'^polls/(\d+)/vote/$', 'blog.views.vote'), 
    url(r'^revote/(\d+)/$', 'blog.views.vote_again'), 

) 

views.py:

# main view for the posts 
def main(request): 
    posts = Post.objects.all().order_by("-created") 
    paginator = Paginator(posts, 5) 

    try: page = int(request.GET.get("page", '1')) 
    except ValueError: page = 1 

    try: 
     posts = paginator.page(page) 
    except (InvalidPage, EmptyPage): 
     posts = paginator.page(paginator.num_pages) 
    d = dict(posts=posts, user=request.user, 
      post_list=posts.object_list, months=mkmonth_lst()) 

    return render_to_response("list.html", d) 

def post(request, pk): 
    post = Post.objects.get(pk=int(pk)) 
    comments = Comment.objects.filter(post=post) 
    try: 
     poll = Poll.objects.get(post=post) 
    except Poll.DoesNotExist: 
     poll = None 
    d = dict(post=post, comments=comments, form=CommentForm(), user=request.user, 
      months=mkmonth_lst(), poll=poll) 
    d.update(csrf(request)) 
    return render_to_response("post.html", d) 


#view to vote on the poll 
def vote(request, post_id): 
    global choice 
    p = get_object_or_404(Poll, pk=post_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=[post_id ])) 

def vote_again(request, post_pk): 
    try: 
     p = get_object_or_404(Poll, post_id=post_pk) 
    except (KeyError, Poll.DoesNotExist): 
     pass 
    else: 
     p.voted = False 
     p.save() 
    return HttpResponseRedirect(reverse("blog.views.post", args=[post_pk])) 

這是正在發生的事情:

post1 - linked to - poll1 
post2 - not linked 
post3 - linked to - poll2 

當我投票關於鏈接到post3的poll2時,它更新poll2的數據庫,但它重新加載post2而不是post3。

+2

你可以是任何更具體?你是否在所有可能不適用的範圍內縮小範圍?你有什麼嘗試?你有沒有在調試器'pdb'中放入代碼?你必須幫助我們一點點來幫助你! – dm03514 2012-08-09 00:00:15

+1

我不確定你在這裏遇到的確切問題。此外,它無法加載您的整個代碼庫。 – 2012-08-09 00:00:36

+0

我試着將pk,poll_pk,poll_id,post pk傳遞給視圖函數,有時候我會得到一個錯誤,但是它的工作時間還剩餘時間,但是重新載入了有投票的id的帖子。 – lciamp 2012-08-09 01:04:26

回答

1

在您的HTML表單中,您的操作設置爲/polls/{{ poll.id }}/vote/。但是,它正在尋找post.pk值,而不是poll.pk。它使用該值在提交數據後重新加載頁面。那應該是你的問題。

編輯

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=[ p.post.pk ]) 
+0

這就給了我一個404「沒有民意調查匹配給定的查詢」這是我一直在獲得除了加載投票的ID的職位。 – lciamp 2012-08-09 01:36:05

+1

這是因爲在你的'vote()'視圖中你使用'post_id'來查詢一個Poll。 – 2012-08-09 01:37:08

+0

謝謝,如果我原來的問題不明確,我很抱歉。我很感激你幫助我。 – lciamp 2012-08-09 02:19:05