2010-07-03 49 views
0

我正在做一個小投票系統,至少可以投票答案,但只有一次。我還沒有創建投票表格,我正在創建投票,當有人提交它(訪問鏈接) 在我的情況下,我怎麼能讓一個人只能投票一次? 如果我改變形式會更好? 我的代碼:Django創建對象只有一次由用戶ID

def voteup(request,classname, id): 
    answer = Answer.objects.get(pk = id) 
    c = Classroom.objects.get(classname = classname) 
    voted_up_by = Membership.objects.filter(classroom = c).get(member = request.user) 
    vote = VoteUpAnswer.objects.create(answer = answer, voted_up_by = voted_up_by) 
    url = reverse('inside_classroom', kwargs={'classname': classname}) 
    return HttpResponseRedirect(url) 

謝謝!

回答

3

我假設voted_up_by種定義投票的用戶。如果是這樣,您可以檢查是否已添加投票。例如

try: 
    VoteUpAnswer.objects.get(voted_up_by = voted_up_by) 
except VoteUpAnswer.DoesNotExist: 
    # No vote from "voted_up_by" exists 
    VoteUpAnswer.objects.create(answer = answer, voted_up_by = voted_up_by) 
else: 
    # User already voted. Redirect to an error page, for example. 
+0

是真的!作品!謝謝!:) – dana 2010-07-03 11:01:24