user1319936
user1319936

Reputation:

Check if current user has voted

On my index page I need to know if the current user has voted on a book, so I can set a class on the <li> elements the current user has already voted on.

Template (snippet)

{% if top_books %}
<ul>
    {% for book in top_books %}
        <li id="{{ book.id }}" class="book">
                <img class="upvote {% ifequal thisUserUpVote 1 %}selected{% endifequal %}" title="Upvote book (click to undo)" src="{{ STATIC_URL }}images/upvote.png" />
                {{ book.score|floatformat }}
                <img class="downvote {% ifequal thisUserDownVote 1 %}selected{% endifequal %}" title="Downvote book (click to undo)" src="{{ STATIC_URL }}images/downvote.png" />
            <a href="/p/{{ book.id }}/">{{ book.title }}</a>
        </li>
    {% endfor %}
</ul>

Views.py (snippet)

from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from books.models import Book

def index(request):
    latest_book = Book.objects.all().order_by('-pub_date')[:5]
    top_items = Book.objects.all().order_by('-score')[:100]
    return render_to_response('books/index.html', {
                            'latest_books': latest_books,
                            'top_books' : top_books},
                            context_instance=RequestContext(request))

Models.py (snippet)

class Book(models.Model):
    title = models.CharField(max_length=500)
    pub_date = models.DateField()
    author = models.ManyToManyField(Author)
    userUpVotes = models.ManyToManyField(User, blank=True)
    userDownVotes = models.ManyToManyField(User, blank=True)

Upvotes: 2

Views: 416

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174642

First, your code won't render correctly since you are passing variables to the template that don't exist in your view - I hope this is just a typo.

def index(request):
    latest_book = Book.objects.all().order_by('-pub_date')[:5]
    top_items = Book.objects.all().order_by('-score')[:100]
    return render_to_response('books/index.html', {
                            'latest_books': latest_books, # latest_book
                            'top_books' : top_books}, # top_items
                            context_instance=RequestContext(request))

For your question - you need to check if a user is userUpVotes or userDownVotes for the model, in your loop in the template:

{% for book in top_books %}
   {% if user in book.userupvotes.all %}
       {{ user }} has upvoted
   {% endif %}
   {% if user in book.userdownvotes.all %}
       {{ user }} has downvoted
   {% endif %}
{% endfor %}

Upvotes: 1

Related Questions