Hi everyone,
I am trying to keep track of who has voted on a comment by setting session variables like 'commentvote1', 'commentvote2', etc to True. These variable names are dynamically generated based on the id of the comment. How can I access these dynamic variables in my template? I've tried this but it doesn't seem to work:
views.py
def comment_upvote(request, comment_id):
comment = get_object_or_404(Comment.objects.filter(id__exact=comment_id,approved=True))
if 'commentvote' + str(comment.id) not in request.session:
comment.upvotes = comment.upvotes + 1
comment.votes = comment.votes + 1
comment.save()
request.session['commentvote' + str(comment.id)] = True
else:
messages.error(request, 'You have already voted on this comment.')
return redirect('comments')
The logic in the view is confirmed to work - It won't let you vote on the same comment twice.
template
{% with 'commentvote'|add:comment.id as voted %}
{% if not request.session.voted %}
<button type="button" class="btn btn-success" aria-label="Vote Up"
onclick="javascript:document.location.href='{% url 'comment_upvote' comment.id %}';">
<span class="glyphicon glyphicon-arrow-up" aria-hidden="true"></span>
</button>
<button type="button" class="btn btn-danger" aria-label="Vote Down"
onclick="javascript:document.location.href='{% url 'comment_downvote' comment.id %}';">
<span class="glyphicon glyphicon-arrow-down" aria-hidden="true"></span>
</button>
{% endif %}
{% endwith %}
Any help would be appreciated!