why my upvote button only works for the first post?

I follow the instruction in tangowithdjango to add a 'like' button into my forum app.

the html file and javascript:

    var postid;
    postid = $(this).attr("data-r-id");
    $.get('/upvote/', {post_id: postid}, function(data){
<a id="upvote" data-r-id="{{r.id}}" class="label-info label pull-right">?<div id="like_count">{{r.upvotes}}</div></a>


def upvote(request):
    post_id = None
    if request.method == 'GET':
        post_id = request.GET['post_id']
    votes = 0
    if post_id:
        p = post.objects.get(id=post_id)
        if p :
            votes = p.upvotes + 1
            p.upvotes = votes
    return HttpResponse(votes)


urlpatterns = patterns(
    url(r'^upvote/$', 'upvote', name='upvote'),

when click the #upvote button ,the #like_count increase by one . However , it works just for the first post. If I click the rest of posts , I get no response at all.

Answers 1

  • I suggest you to give upvote as class not as id because id refers an unique element in your document.

        var postid;
        postid = $(this).attr("data-r-id");
        $.get('/upvote/', {post_id: postid}, function(data){
                   $('#like-count-' + postid).html(data);

    and your html should look like,

    <a data-r-id="{{r.id}}" class="label-info label pull-right upvote">?<div id="like-count-{{r.id}}">{{r.upvotes}}</div></a>

Related Articles