我会回答你的问题,但首先你真的有点不对劲。您构建此结构的方式没有一个很好的方法来监督一个人投票的次数。即使人们从不故意玩弄这个,也不可避免地会出现导致人们多次投票给某件事的错误。
理想情况下,像这样设置第二个表(假设您只是轮询登录的用户):
class Vote(models.Model):
user = models.ForeignKey("User")
comment = models.ForeignKey("Comments")
score = models.IntegerField(default=0)
然后您将拥有一个按钮,该按钮可以提交带有 +1 或 -1 的简单单字段表单视图。 “分数”将是一个简单的总和,或者您可以计算正值和负值以获得有多少赞成或反对的值。
如果这是一个具有任何意义的应用程序,您应该使用 REST api(我喜欢 Tastypie,但还有其他的)。放下第一个 API 有点费力,但还不错,除非您的应用非常简单,否则值得投资。
所以最后......死的简单的黑客/愚蠢的方式来做到这一点。您不需要表格,只需使用generic View
将其添加到 urls.py 中,使用正常的 url 和 comment_id 作为 kwarg
url(r'^vote/(?P<comment_id>\d+)/$', BoneheadView.as_view(), name='comments-vote'),
在views.py中:
class BoneheadView(View):
def post(self, comment_id):
if "vote" in self.request.POST:
vote = int(self.request.POST["vote"])
if vote_score in (-1, 0, 1):
# Do something to save your vote here like:
(vote,created) = Vote.objects.get_or_create(comment_id=comment_id)
vote.score = vote_score
vate.save()
return HttpResponse("Yay, a Vote")
else:
return HttpResponse("Invalid Vote", status=400)
else:
return HttpResponse("Invalid Vote", status=400)
最后,在您的页面上:
修改后的 HTML
<div class="vote_div">
<a href="{% url 'comments-vote' comment.id %}" data-score="1" class="vote"><img src="upvote.png" /></a>
<a href="{% url 'comments-vote' comment.id %}" data-score="-1" class="vote"><img src="downvote.png" /></a>
</div>
(在你的页面上把这个放在</body>之前)
<script>
$(".vote").click(function() {
var element = $(this); // grab the object that triggered the event
$.post(element.attr('href'), { score: element.data('score')});
return false;
})
</script>