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>
<span class="glyphicon glyphicon-arrow-down" aria-hidden="true"></
</button>
{% endif %}
{% endwith %}
Any help would be appreciated!
I think you have the wrong data structure. Instead of storing all the comment votes as separate keys in the session, consider storing them in a single "commentvotes" dictionary:
votes = request.session.setdefault('commentvotes', {})
if comment.id not in votes:
...
votes[comment.id] = True
else:
...
and the template:
{% if comment.id not in request.session.votes %}
--
Daniel.
-- You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/19223e2f-f70b-43d7-8f60-a9cf829512b4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment