I follow the instruction in tangowithdjango to add a 'like' button into my forum app.
the html file and javascript:
<script>
$(document).ready(function(){
$("#upvote").click(function(){
var postid;
postid = $(this).attr("data-r-id");
$.get('/upvote/', {post_id: postid}, function(data){
$('#like_count').html(data);
});
});
});
</script>
<a id="upvote" data-r-id="{{r.id}}" class="label-info label pull-right">赞<div id="like_count">{{r.upvotes}}</div></a>
views.py
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
p.save()
return HttpResponse(votes)
urls.py
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.
I suggest you to give upvote
as class not as id because id refers an unique element in your document.
$(document).ready(function(){
$(".upvote").click(function(){
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>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments