Thursday, July 2, 2015

Access dynamic session variable name in template

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!

--
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/6409d0b4-ac59-4054-95ef-f3a018554148%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment