Hey there! I'm currently working on implementing a voting feature using Ajax in my Django-based website. The issue I'm facing is that users can only vote on the first entry, but I want them to be able to vote on all entries. Can you assist me with modifying the code to achieve this?
Let's start with the HTML code, which simply displays a vote button for users:
{% for answer in answers %}<!-- django template -->
<strong id="vote_count">{{ answer.votes }}</strong> people have voted for this answer
{% if user.is_authenticated %}
<button id="vote" data-answerid="{{answer.id}}" class="btn btn-primary" type="button">
<span class="glyphicon glyphicon-thumbs-up"></span>
Vote
</button>
{% endif %}
{% endfor %}<!-- end django template -->
Next, here's the Django view responsible for processing the voting request:
@login_required
def vote_answer(request):
answer_id = None
if request.method == 'GET':
answer_id = request.GET['answer_id']
votes = 0
if answer_id:
answer = Answer.objects.get(id=answer_id)
if answer:
votes = answer.votes + 1
answer.votes = votes
answer.save()
return HttpResponse(votes)
Here's the URL mapping for this functionality:
url(r'^like_category/$', views.like_category, name='like_category'),
Lastly, check out the JavaScript code below:
$('#vote').click(function(){
var answerid;
answerid = $(this).attr("data-answerid");
$.get('/vote_answer/', {answer_id: answerid}, function(data){
$('#vote_count').html(data);
$('#vote').hide();
});
});
I hope that clarifies things! My main issue remains enabling users to vote on all entries on a single page instead of just the first one.