Django只能通过用户ID创建一次对象

时间:2010-07-03 10:27:07

标签: django object instance

我正在制作一个小投票系统,可以投票给答案,但只有一次。我还没有为投票创建表单,我在有人提交投票时创建投票(访问链接) 在我的情况下,我怎样才能让一个人只能投票一次? 如果我做一个表格会更好吗? 我的代码:

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)

谢谢!

1 个答案:

答案 0 :(得分: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.