我是Django的新手,我正在尝试使用django-vote在{@ 3}}上构建的注释应用程序中实现up / downvotes: 用于实施。但是,或者我不能正确理解django-vote文档,或者我的实现有问题。我在github上浏览了django-vote的源代码,但无济于事。
我已经尝试通过在每一步打印代码来追查错误,并且看来django-vote应用实际上并没有记录投票。如果是这种情况,我可能会尝试从头开始构建另一个,但是不确定。
HTML for the vote buttons:
<i class=" vote upvote increment fas fa-chevron-circle-up" data-userid ="{{ request.user.id }}" data-commentid="{{ comment.id }}" data-action='UP' ></i>
<i class="vote downvote increment fas fa-chevron-circle-down" data-userid ="{{ request.user.id }}" data-commentid="{{ comment.id }}" data-action='DOWN'></i>
JS:
$(".increment").click(function(event){
var v = $(this);
var action = v.data('action');
var commentID = v.data('commentid');
var userID = v.data('userid');
console.log("vote submitted");
console.log(commentID);
console.log(action);
console.log(userID);
$.ajax({
url: "/comments/vote/",
data: { 'csrfmiddlewaretoken' : '{{ csrf_token }}', commentID: commentID,
action: action, userID : userID, },
type: 'POST',
success: function (data) {
console.log(data);
console.log("vote success")},
error: function() {
console.log('vote failure')
}
});
});
Django view function:
@login_required
@require_POST
def comment_vote(request):
if request.method == 'POST':
voting_user = request.POST.get('userID')
comment_id = request.POST.get('commentID')
voteAction = request.POST.get('action')
comment = Comment.objects.get(pk=comment_id)
if voteAction == 'UP':
comment.votes.up(user_id= voting_user)
elif voteAction == 'DOWN':
comment.votes.down(voting_user)
comment.total_score = comment.calculate_vote_score
comment.save()
data = {'user' : voting_user, 'vote' : voteAction,'comment' : comment_id, }
return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder), content_type="application/json")
答案 0 :(得分:0)
我不确定您要完成什么,但是我不确定以下行:
comment.votes.up(user_id= voting_user)
假设您实际上正在视图中获取数据,请尝试以下操作:
from django.db.models import F
comment = Comment.objects.get(pk=comment_id)
if voteAction = 'UP':
comment.update(vote_count_column = F('vote_count_column') + 1)
elif voteAction = 'DOWN':
comment.update(vote_count_column = F('vote_count_column') - 1)
其中vote_count_column
是保存投票计数的整数列。
如果这不起作用,请告诉我。我还有更多想法。