Django create object only once by a user id
I'm making a little vote system, in wich one can vote an answer, but only once. I have not created a form for the vote, i am creating the vote when someone submits it (accesses a link) How can i make, in my situation, for a p开发者_C百科erson to be able to vote only once? It would be better if i would make a form instead? my code:
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)
thanks!
I assume that voted_up_by
kind of defines the user that voted. If that's true, you can check whether a vote has been added yet. For example
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.
精彩评论